繁体   English   中英

Android 工作室,试图用基础 xml 和 ArrayAdapter 膨胀 xml 文件

[英]Android studio, trying to inflate an xml file with a base xml and ArrayAdapter

我正在尝试用 xml 文件填充 xml(聊天日志),以及 class 文件,我可以从中获取消息的文本。

我使用 ArrayAdapter 和通货膨胀。 我有 2 个 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 文件,直到完成。 取而代之的是,id喜欢在ListView中一一对应go,并检查Msg.getMine() = true; 如果是这样,我想用 xml "messageme" 像这样膨胀那个:

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

我怎么能做这样的事情?

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()”......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM