本文介绍了Android从ListView获取复选框信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有多个复选框的ListView(每个列表项一个)。创建包含选定复选框中信息的数组的最佳方法是什么。
I have a ListView with multiple checkboxes (one for each list item). What would be the best way to create an array containing information from the selected checkboxes.
例如,下面是列表。
Item 1 "Ham" Checked
Item 2 "Turkey" NotChecked
Item 3 "Bread" Checked
我想创建一个包含火腿和火鸡的数组
I would like to create an array containing "ham" and "turkey"
推荐答案
如果您将ListView的内置复选框方法与setChoiceMode()一起使用,则只需调用或。
If you used ListView's built-in checkbox method with setChoiceMode() then you only need to call getCheckedItemIds() or getCheckedItemPositions().
public class Example extends Activity implements OnClickListener {
ListView mListView;
String[] array = new String[] {"Ham", "Turkey", "Bread"};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, array);
mListView = (ListView) findViewById(R.id.list);
mListView.setAdapter(adapter);
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
public void onClick(View view) {
SparseBooleanArray positions = mListView.getCheckedItemPositions();
int size = positions.size();
for(int index = 0; index < size; index++) {
Log.v("Example", "Checked: " + array[positions.keyAt(index)]);
}
}
}
如果适配器绑定到光标,然后变得更加实用。
If the Adapter is bound to a Cursor, then this becomes much more practical.
这篇关于Android从ListView获取复选框信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!