取消选中其中一个CheckBox后,在ListView中选中已检查的项目?

时间:2012-04-11 00:05:17

标签: android android-listview checkbox

我正在尝试获取ListView中已检查的项目。这里的问题是,当我在取消选中之后尝试获取项目时,它会显示所有已检查且未选中的元素。例如,如果我检查选项A,B和C并获取已检查项目的列表,则结果为3,如果我在取消选中选项B后尝试,我仍然得到结果为3.这是我的代码:

public class ClikableList extends Activity implements OnItemClickListener{
/** Called when the activity is first created. */
ListView lv;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

     lv = (ListView) findViewById(R.id.listView1); 
    lv.setAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_multiple_choice, GENRES));
    lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    lv.setOnItemClickListener(this);


}

private static final String[] GENRES = new String[] {
    "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
    "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
};

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {

    //Toast.makeText(getBaseContext(),lv.getItemAtPosition(position) + " Test "+lv.getCheckedItemPositions().size(), Toast.LENGTH_SHORT).show();        
        System.out.println(lv.getItemAtPosition(position)); 
    lv.updateViewLayout(arg1, null);

}}

2 个答案:

答案 0 :(得分:1)

我不知道你是如何获得检查项目的,但是你应该使用方法getCheckedItemPositions()来获取用户在ListView中检查的位置:

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
        SparseBooleanArray checkedPosistions = lv.getCheckedItemPositions(); // this will return a mapping of the position in the adapter and a boolean value
        String results = "";
        int count = lv.getAdapter().getCount();
        for (int i = 0; i < count; i++) {
            if (checkedPositions.get(i)) { //if true this is a checked item
                results += i + ",";
            }
        }
        Toast.makeText(this, "The checked items are :" + results,
                Toast.LENGTH_SHORT).show();
        // ...
}}

答案 1 :(得分:1)

你确定这个工作正常吗?

因为据我所知,您需要使用checkedPositions.valueAt(i)代替checkedPositions.get(i)