2013-02-27 92 views
2

我有一個android應用程序,它使用listview.Each行由ImageView,TextView和CheckBox組成。 我想從這個listview.I獲得所選項目二手如何從android listview中檢查項目?

private void getSelectedItems() { 
     List<String>list = new ArrayList<String>(); 
     try { 
      SparseBooleanArray checkedItems = new SparseBooleanArray(); 
      checkedItems = listView.getCheckedItemPositions(); 
      if (checkedItems == null) { 
       return; 
      } 
      final int checkedItemsCount = checkedItems.size(); 
      for (int i = 0; i < checkedItemsCount; ++i) { 
       int position = checkedItems.keyAt(i); 
       boolean bool = checkedItems.valueAt(position); 
       if (bool) { 
        list.add(mainList.get(position)); 
       } 
      } 

     } catch (Exception e) { 

     } 
    } 

但我想設定一些項目如相對於檢查在啓動理想管材檢查項目獲得的條件,只有當如果用戶選擇/取消一個item.No檢查項目獲取即使該項目設置爲在程序啓動時檢查。這裏的問題是什麼?

由於提前

回答

3

做這樣的事情,

ArrayList<Integer> checkedPositions = new ArrayList<Integer>(); 
myListView.setOnItemClickListener(new OnItemClickListener() { 

      @Override 
      public void onItemClick(AdapterView<?> arg0, View view, 
        int position, long arg3) { 
       CheckBox cb = (CheckBox) view.findViewById(R.id.yourCheckBox); 
       Toast.makeText(getApplicationContext(), "Row " + position + " is checked", Toast.LENGTH_SHORT).show(); 
       if (cb.isChecked()) { 
        checkedPositions.add(position); // add position of the row 
                // when checkbox is checked 
       } else { 
        checkedPositions.remove(position); // remove the position when the 
              // checkbox is unchecked 
        Toast.makeText(getApplicationContext(), "Row " + position + " is unchecked", Toast.LENGTH_SHORT).show(); 
       } 
      } 
     }); 
+0

Ok.Here我沒有選擇任何項目manually.ie,我沒點擊列表視圖items.but作爲prgmmatically檢查設置項目。那我怎麼能得到檢查的項目? – 2013-02-27 11:40:46

+0

@Srujan Simha else if語句不需要,因爲它意味着checkBox已經被選中,使用else {...}。此外,這一行給出錯誤:cb.remove(position);或者將其編輯爲:checkedPositions.remove(position); 。我編輯了這個答案,但你不同意,雖然它的需要。 – blueware 2015-04-26 06:30:19

+0

我們可以得到已經檢查過的值並在listview中顯示它們嗎? @Srujan Simha – 2015-12-03 03:23:53

相關問題