cursoradapter with different row layouts

后端 未结 3 1686
心在旅途
心在旅途 2020-12-02 08:08

I\'m trying to create a custom cursoradapter that will use two different layouts depending on some data in the cursor. I keep reading about \'overriding getViewTypeCount() a

相关标签:
3条回答
  • 2020-12-02 08:25

    Another possible solution regarding the access to the cursor in the getItemViewType method is the following:

    @Override
    public int getChildType(int groupPosition, int childPosition) {
        Cursor c = getChild(groupPosition, childPosition);
        if(c.getString(c.getColumnIndex(Contract.MyColumn)).equals("value"))
            return 0;
        else return 1;
    }
    
    0 讨论(0)
  • 2020-12-02 08:32

    Take a look to this example, you can easily adapt it for solving your problem. It's pretty straightforward.

    0 讨论(0)
  • 2020-12-02 08:40

    So I finally got it work. For the ones interested the working code is below:

    private int getItemViewType(Cursor cursor) {
        String type = cursor.getString(cursor.getColumnIndex("type"));
        if (type.equals("1")) {
            return 0;
        } else {
            return 1;
        }
    }
    
    @Override
    public int getItemViewType(int position) {
        Cursor cursor = (Cursor) getItem(position);
        return getItemViewType(cursor);
    }
    
    @Override
    public int getViewTypeCount() {
        return 2;
    }
    
    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.textView
                .setText(cursor.getString(cursor.getColumnIndex("body")));
    }
    
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        ViewHolder holder = new ViewHolder();
        View v = null;
    
        if (cursor.getString(cursor.getColumnIndex("type")).equals("1")) {
            v = mInflater.inflate(R.layout.message1, parent, false);
            holder.textView = (TextView) v
                    .findViewById(R.id.textView1);
        } else {
            v = mInflater.inflate(R.layout.message2, parent, false);
            holder.textView = (TextView) v
                    .findViewById(R.id.textView2);
        }
    
        v.setTag(holder);
        return v;
    }
    
    public static class ViewHolder {
        public TextView textView;
    }
    
    0 讨论(0)
提交回复
热议问题