Ali
Ali

Reputation: 9994

Listener for CheckedTextView in ListView

I created a simple ListView includes checkedTextView.

I want to add a listener when user click on listView row,

1 - The textView become checked.

2 - If there is another textview in the list which were checked, become unchecked.

This is the code which I written until now:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ArrayList<String> mStrings = new ArrayList<String>();
        for(int i=0; i<30; i++) {
            mStrings.add("Item " + i);
        }

        setListAdapter( new MultiAdapter(this, mStrings));

        /* Configure ListView */
        ListView lv = getListView();
        lv.setOnItemClickListener(new ItemClick());
    }

    class ItemClick implements OnItemClickListener {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        }
    }

    private class MultiAdapter extends ArrayAdapter<String> {

        private ArrayList<String> mItems;

        public MultiAdapter(Context context, ArrayList<String> mStrings) {
            super(context, R.layout.list2, mStrings);
            this.mItems = mStrings;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View row;

            if (convertView == null)  {
                LayoutInflater inflater = getLayoutInflater();
                row = inflater.inflate(R.layout.list2, parent, false);
            } else
                row = convertView;

            CheckedTextView txt = (CheckedTextView) row.findViewById(R.id.label);

            txt.setText(mItems.get(position));

            return row;
        }
    } 

Could you help me about the Listener which I need to code?

I couldn't find any tutorial about checkedTextView that can help me. Please let me know if you know some example code or tutorial.

Upvotes: 1

Views: 2957

Answers (2)

Roman Nazarevych
Roman Nazarevych

Reputation: 7703

Past this code in your onCreate method

    lv.setItemChecked(yourDefCheckedPos, true);
    lv.setSelection(yourDefCheckedPos);

And in Listener:

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        parent.setSelection(position);
        ((ListView)parent).setItemChecked(position, true);
    }

Upvotes: 1

Mikita Belahlazau
Mikita Belahlazau

Reputation: 15434

If you want to have only max 1 checked in any give time then you can do following:

  1. Create int checkedItem; property. This property show index of currently checked item. -1 if none is checked.
  2. In ItemClick just set checkedItem = position. And call getListAdapter().notifyDataSetChanged().
  3. In getView add txt.setChecked(position == checkedItem).

Upvotes: 4

Related Questions