0

I am working on a Custom list view with a single choice mode. I have followed the below tutorial and successfully achieved it.

Custom Single Choice ListView

I have a use case where I want to set a particular item is the list to be checked by default, I have tried to do setChecked(true) at the require position in the adapter but it didnt work. Can anybody help me how to achieve it.

Thanks in advance.

Code_Yoga
  • 2,968
  • 6
  • 30
  • 49

1 Answers1

0

This source says:

Basically, the single-choice ListView expects the widgets you provide it with to implement the Checkable interface. LinearLayout et al don't. So you need to create a custom layout that inherits LinearLayout (or whatever layout you want to use for your items) and implements the necessary interface.

And from this source you can set it by using custom adapter inside your Activity:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // set the choice mode
    final ListView list = getListView();
    list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    // custom adapter
    list.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item,
            R.id.title, text) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = super.getView(position, convertView, parent);
            ImageView icon = (ImageView) v.findViewById(R.id.img);
            if (list.isItemChecked(position)) {
                icon.setImageResource(R.drawable.checked);
            } else {
                icon.setImageResource(R.drawable.unchecked);
            }
            return v;
        }
    });
}

However this version has some performance issues - findViewById and setImageResource are relatively time-consuming operations so you should consider using some caching.

Hope it helps for you.

Community
  • 1
  • 1
Anggrayudi H
  • 14,977
  • 11
  • 54
  • 87