0

我正在尝试获取在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);

}}
4

2 回答 2

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();
        // ...
}}
于 2012-04-11T04:58:06.240 回答
1

你确定这工作正常吗?

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

于 2012-05-27T01:12:08.690 回答