AndroidStudio,尝试使用基本xml和arrayadapter来膨胀xml文件

fae0ux8s  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(351)

我正在尝试用一个xml文件(聊天日志的)填充一个xml文件,其中包含一个可以从中获取消息文本的类。
我正在使用阵列适配器和通货膨胀。我有两个xml文件,其中一个是“messageother”,它代表其他人的消息,而“messageme”代表用户自己编写的消息。

public class MsgAdapter extends ArrayAdapter<Msg> {

    private final Context context;
    private final ArrayList<Msg> msgList;

    private TextView tvText;

    public MsgAdapter(Context context, ArrayList<Msg> messages) {
        super(context, R.layout.activ, messages);
        this.context=context;
        this.msgList=messages;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.messageother, parent, false);

        return rowView;
    }
}

现在,这将只是复制“messageother”的同一个xml文件,直到它完成。相反,我想在listview中逐个检查msg.getmine()=true;如果是这样的话,我想用xml“messageme”将其放大如下:

View rowView = inflater.inflate(R.layout.messageme, parent, false);

我怎么能做这样的事?

4xrmg8kj

4xrmg8kj1#

public static class MsgAdapter extends ArrayAdapter<Msg> {
    private static final class ViewHolders {
        View mMessageOthersView;
        View mMessageMeView;
        private ViewHolders(@NonNull final LayoutInflater layoutInflater, @NonNull View parent) {
            this.mMessageOthersView = layoutInflater.inflate(R.layout.messageother, parent, false);
            this.mMessageMeView = layoutInflater.inflate(R.layout.messageme, parent, false);
        }
    }

    private final ArrayList<Msg> msgList;
    private final LayoutInflater mLayoutInflater;

    public MsgAdapter(Context context, ArrayList<Msg> messages) {
        super(context, R.layout.activ, messages);
        this.msgList = messages;
        this.mLayoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        final ViewHolders cViewHolders;
        if (convertView == null) {
            cViewHolders = new ViewHolders(this.mLayoutInflater, parent);
            convertView.setTag(cViewHolders);
        } else {
            cViewHolders = (ViewHolders)convertView.getTag();
        }

        final View finalView;
        final Msg cMsg = this.getItem(position);
        if (cMsg.getMine()) finalView = cViewHolders.mMessageMeView;
        else finalView = cViewHolders.mMessageOthersView;

            //"finalView" is the final inflated Layout
        finalView.findViewById(....)

        return finalView;
    }
}

下一步可能是缓存每个布局所需的所有视图,避免对每个项执行完整的“findbyid()”。。。。。。

相关问题