Search code examples
javaandroidlistviewmultiple-choice

how to set checked="checked" item in simple_list_item_multiple_choice in my list, if I want that 2 element was always checked?


    private ListView LVmain;

    private ArrayList<String> tasks = new ArrayList<String>();
    private ArrayAdapter<String> adapter;

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice, tasks);
tasks.add("first");
tasks.add("second");
tasks.add("thirst");
tasks.add("fourth");
adapter.notifyDataSetChanged();

}

So I want that second item was already checked when I start the program


Solution

  • Wherever you assign the adapter to your ListView, try this:

    LVmain.setItemChecked(1, true);
    LVmain.setSelection(1);
    

    Note that we're passing 1 to check the second item, since list view positions are 0-based.