开发者

(Pre)select checkboxes in a ListActivity using 'simple_list_item_checked'

I'm using the ListActivity class in conjunction with the simple_list_item_checked-layout which implements simple list items with checkboxes. Everything is working fine - clicking added items calls onListItemClick() and I can check/uncheck respective checkboxes of entries via the 'View v' parameter.

However what I wasn't able to figure out yet is, how to (pre)select checkboxes without any userinteraction?

Minimal so far working code snippet showing my intend:

package org.test;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;

public class TestActivity extends ListActivity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ArrayAdapter<String> list_elems = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked);
        list_elems.add("foobar");
        //TODO: check added entry labeled "foobar"
        setListAdapter(list_elems);
    }

    protected void onListItemClick(ListView l, View v, int position, long id) {
       开发者_JAVA技巧 super.onListItemClick(l, v, position, id);
           CheckedTextView check = (CheckedTextView)v;
        check.setChecked(!check.isChecked());
    }
}

Thanks a lot in advance!

daten


This works for me:

You have to set the choicemode of the underlying ListView to single or multiple.

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ArrayAdapter<String> list_elems = new ArrayAdapter<String>(this, Android.R.layout.simple_list_item_checked);
        list_elems.add("foobar");
        //TODO: check added entry labeled "foobar"
        setListAdapter(list_elems);

        ListView lv = getListView();

        lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        lv.setItemChecked(0, true);
    }


Use a SimpleListAdapter as the ListAdapter for your ListActivity. Use two columns (one for your string and the other for the checked value), and the system should take care of it by itself. Here is a good example

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜