CheckedTextView checkmark in ListView row not showing up

后端 未结 1 1552
既然无缘
既然无缘 2020-12-12 00:06

I have a problem with the Checkmark of my ListView row layout. The checkmark doesn\'t show up when the ListItem is clicked even though the ListView works (the interaction wo

1条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-12 01:08

    You will want to make you custom row layout that is checkable.

    First you need to create a custom layout that implements Checkable:

    public class CheckableLinearLayout extends LinearLayout implements Checkable {
        private Checkable mCheckable;
    
        public CheckableLinearLayout(Context context) {
            this(context, null);
        }
    
        public CheckableLinearLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        @Override
        public boolean isChecked() {
            return mCheckable == null ? false : mCheckable.isChecked();
        }
    
        @Override
        protected void onFinishInflate() {
            super.onFinishInflate();
    
            // Find Checkable child
            int childCount = getChildCount();
            for (int i = 0; i < childCount; ++i) {
                View v = getChildAt(i);
                if (v instanceof Checkable) {
                    mCheckable = (Checkable) v;
                    break;
                }
            }
        }
    
        @Override
        public void setChecked(boolean checked) {
            if(mCheckable != null)
                mCheckable.setChecked(checked);
        }
    
        @Override
        public void toggle() {
            if(mCheckable != null)
                mCheckable.toggle();
        }
    }
    

    After this layout is inflated it looks through it's children for one that is checkable (like a CheckedTextView or CheckBox), other than that it is quite simple.

    Next use it in a layout:

    
    
        
    
        
    
    
    

    Notice that you cannot just use CheckableLinearLayout, since it is not a built-in Android View you need tell the compiler where it is. Save this as checkable_list_row.xml, for example.

    Lastly use this new layout like you would with any other custom layout.

    adapter = new MySimpleCursorAdapter(this, R.layout.checkable_list_row, cursor,
            new String[] { Database.KEY_DATE , Database.KEY_NAME },
            new int[] {R.id.text1, R.id.text2}, 0);
    

    Hope that helps!

    0 讨论(0)
提交回复
热议问题