2012-04-11 58 views
0

我試圖獲取在ListView中檢查的項目。這裏的問題是,當我在取消選中項目後嘗試獲取項目時,它會顯示所有已選中並且未選中的元素。例如,如果我檢查選項A,B和C並獲得檢查項目列表,則結果爲3,則如果我在取消選中選項B後嘗試,我仍然會得到結果爲3.以下是我的代碼:取消選中其中一個複選框後,在ListView中選中選中的項目?

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); 

}} 
+0

過得好檢查項目列表中使用checkedPositions.valueAt(i)? – Macarse 2012-04-11 04:16:04

+0

檢查此鏈接http://www.vogella.de/articles/AndroidListView/article.html(主題No 8.教程:領域模型和行交互) – 2012-04-11 11:25:15

回答

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

真棒老兄謝謝....工作很棒... – kAnNaN 2012-04-11 19:51:23

1

你確定這是否正常?

,因爲據我所知,你需要到位的checkedPositions.get(i)

相關問題