1

我目前正在爲我的android應用實施多選ListView。我的目標是在點擊搜索按鈕時,從與ListView關聯的ArrayAdapter中檢索所選項目。從多選ListView中檢索所選項目

我目前難住如何做到這一點,我發現在線的東西,如試圖設置MultiChoiceModeListener,但這似乎並沒有出現在Eclipse作爲一個選項。我正在使用Google API s(等級10),Android 2.3.3等效。這裏是我到目前爲止的代碼:

public class FindPlace extends Activity {  

    public FindPlace() {} 

    @Override 
    protected void onCreate(Bundle savedInstanceState) {    
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.list_places); 
     Button search = (Button) findViewById(R.id.search); 
     String[] categories = getResources().getStringArray(R.array.Categories); 
     ArrayAdapter ad = new ArrayAdapter(this,android.R.layout.simple_list_item_multiple_choice,categories); 
     final ListView list=(ListView)findViewById(R.id.List); 
     list.setAdapter(ad); 
     list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 
     list.setOnItemClickListener(new OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } 

     });  
    }  
} 

回答

0

將int中所選項目的計數和make for循環如下所示。

int len = listView.getCount(); 
SparseBooleanArray checked = listView.getCheckedItemPositions(); 
for (int i = 0; i < len; i++){ 
if (checked.get(i)) { 
     String item = cont_list.get(i); 
     /* do whatever you want with the checked item */ 
    } 
} 
0

稍微更有效/正確:

SparseBooleanArray checked = listView.getCheckedItemPositions(); 
for (int i = 0; i < checked.size(); ++i) 
{ 
    if (checked.valueAt(i)) 
    { 
     int pos = checked.keyAt(i); 
     doSomethingWith(adapter.getItem(pos)); 
    } 
}