1

如果我的ListView的佈局在下面,每個項目都有一個複選框,那麼當我點擊Button時,如何獲得onClick()方法中的所有選中項目?從ListView中獲取所有選中的項目

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical"> 

     <ListView 
      android:id="@+id/listview" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      /> 

    </LinearLayout> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Submit" 
     android:onClick="submitList" 
     /> 

</RelativeLayout> 

onClick()方法:

public void submitList(View view) { 
    // 
} 
+0

你到目前爲止試過的東西? – Amy

+0

請參閱以下內容[Android - 從ListView中使用CheckBox獲取所選項目](http://kb4dev.com/tutorial/android-listview/checkbox-in-listview--event-handling--1) –

回答

0

您可以使用SparseBooleanArray如果您使用的是ListView.CHOICE_MODE_MULTIPLE得到檢查的項目。 以下是StackoverFlow question的參考資料。

1

您可以檢查列表視圖項目一個接一個:

for (int i=0; i < listview.getAdapter().getCount(); i++) { 
listview.setItemChecked(i, true); 
} 
+0

即使對於行那是不可見的? – CDrosos

0

你必須做出一個ArrayList中與你的ListView適配器的大小。之後,當你檢查你的任何列表項時,在數組列表中添加該項。

public ArrayList<String> getCheckedName() 
    { 
     return array_list; 
    } 

將此函數寫入您的適配器類。當你想要檢查數據呼叫

ArrayList<String> sName=adapter.getCheckedName(); 

在onClick方法中使用此sName。

0
int len = listview.getCount(); 
SparseBooleanArray checked = listview.getCheckedItemPositions(); 
for (int i = 0; i < len; i++) { 
    if (checked.get(i)) 
     String item = yourArrayList.get(i); 
}