How to use the same RecyclerView Adapter for different layouts

后端 未结 4 2091
逝去的感伤
逝去的感伤 2021-02-09 06:48

I am developing an application which heavily relies on the usage of RecyclerView.

I really need to know how to use the same RecyclerView for different item layouts. An e

4条回答
  •  日久生厌
    2021-02-09 07:12

    //To setViewType maybe is a solution for you.Sample below:  
    private static final int TYPE_DESC = 0;
    private static final int TYPE_IMAGE = TYPE_DESC + 1;
    private static final int TYPE_THREE_TEXT = TYPE_IMAGE + 1;
    public int getItemViewType(int position) {
        int type = super.getItemViewType(position);
        try
        {
            type = Integer.parseInt(data.get(position).get("type"));
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return type;
    }
    
    public int getViewTypeCount() {
        return 3;
    }
    public View getView(int position, View convertView, ViewGroup parent) {
        int type = TYPE_DESC;
        try
        {
            type = Integer.parseInt(data.get(position).get("type"));
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        ViewHolder holder = null;
        if (convertView == null)
        {
            System.out.println("getView::convertView is null");
            holder = new ViewHolder();
            switch (type)
            {
                case TYPE_DESC:
                    convertView = View.inflate(getBaseContext(),
                            R.layout.listitem_1, null);
                    break;
                case TYPE_IMAGE:
                    convertView = View.inflate(getBaseContext(),
                            R.layout.listitem_2, null);
                    break;
                case TYPE_THREE_TEXT:
                    convertView = View.inflate(getBaseContext(),
                            R.layout.listitem_3, null);
                    break;
            }
            convertView.setTag(holder);
        }
        else
        {
            holder = (ViewHolder) convertView.getTag();
        }
        //TODO
        return convertView;
    }
    

提交回复
热议问题