Search code examples
androidandroid-listviewandroid-cursoradapter

set row background on checkbox clicked inside listview


I have listview with 2 textbox and 1 checkbox on each row. I want when a user check the checkbox, then a predefined drawable is to be set as a background to that row.

I have tried to do it on the Lisnner on the getView method inside my cusotm cursor adapter, but with no success, please help!!!.


Solution

  • Use this getView method in your ListAdapter:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.list_item, null);
        CheckBox checkBox = (CheckBox) view.findViewById(R.id.check);
        checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                View row = (View) buttonView.getParent();
                if (isChecked) {
                    row.setBackgroundResource(R.drawable.list_item_background_checked);
                } else {
                    row.setBackgroundResource(android.R.color.transparent);
                }
            }
        });
        return view;
    }