ListViewからチェックボックス情報を取得します
-
29-10-2019 - |
質問
各行のチェックボックスを備えたレイアウトを備えたリストフラグメントを含むアクティビティがあります。私は設定します onclick
チェックボックスのXML属性とテストのために以下を実行します
public void onBoxClick(View v){
checkedItems = listview.getCheckedItemPositions();
int checkedItemsCount = checkedItems.size();
}
checkedItemsCount
戻ってくる 0
, 、私はあなたが使用するチェックされたアイテムを取得すると思いました listview.getCheckedItemPositions()
しかし、そうではありません。リストでチェックされているものを知るにはどうすればよいですか?
これが私のリスト戦の作成です
@Override
public void onActivityCreated(Bundle state){
super.onActivityCreated(state);
listview = getListView();
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listview.setItemsCanFocus(false);
setEmptyText("No Bowlers");
registerForContextMenu(getListView());
populateList();
}
解決 2
カスタムアダプターで問題を回避しました bindView
, 、私は作成しました ArrayList<Integer>
変数
ArrayList<Integer> mCheckedItems = new ArrayList<Integer>();
とで bindView
設定します checkedchangelistener
チェックボックスで、ボックスがチェックされているかどうかを確認します。チェックされた場合、カーソルが入ったデータベースからIDを入れました mCheckedItems Array
アダプタ:
public class CheckAdapter extends SimpleCursorAdapter{
Context context;
public CheckAdapter(Context context, int layout, Cursor c,String[] from, int[] to,int flag) {
super(context, layout, c, from, to);
this.context = context;
}
@Override
public void bindView(View view,Context context,Cursor cursor){
final String name = cursor.getString(cursor.getColumnIndex(BowlersDB.NAME));
final int id = cursor.getInt(cursor.getColumnIndex(BowlersDB.ID));
TextView tv = (TextView)view.findViewById(R.id.nameCheckTV);
tv.setText(name);
CheckBox cb = (CheckBox)view.findViewById(R.id.checkBox1);
cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked){
mCheckedItems.add(id);
}else if(!isChecked){
for(int i=0; i< mCheckedItems.size(); i++){
if(mCheckedItems.get(i) == id){
mCheckedItems.remove(i);
}
}
}
}
});
}
IDが配列に挿入された後、配列リストを使用して必要な方法を使用しました
他のヒント
これ 役職 役立つかもしれません。カスタムを使用したソリューションを提供します ResourceCursorAdapter
, 、aを提供します CheckBox
そしてa TextView
それぞれのため ListView
行。
複数のアイテムを選択します ListView
, 、 これをチェックして ページ. 。この例ではaを使用していることに注意してください ListActivity
aの代わりに ListFragment
, 、しかし、あなたのコードは非常に似ています。必ず実装してください Fragment
ライフサイクル方法は正しく(つまり、のアダプターを設定します ListFragment
's onActivityCreated()
, 、など)。