簡體   English   中英

Select 取消選中其中一個復選框后,ListView 中選中的項目?

[英]Select the checked items in a ListView after unchecking one of the CheckBoxes?

我正在嘗試獲取在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);

}}

我不知道你是如何獲得選中的項目的,但你應該使用方法 getCheckedItemPositions getCheckedItemPositions()來讓用戶在ListView中檢查 position :

@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();
        // ...
}}

你確定這工作正常嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM