要实现多选选择框,你可以使用Android中的ListView控件和自定义Adapter来实现。以下是一个简单的示例代码,演示如何实现多选选择框:
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
public class CustomAdapter extends BaseAdapter {
private Context context;
private List<String> items;
private SparseBooleanArray selectedItems;
public CustomAdapter(Context context, List<String> items) {
this.context = context;
this.items = items;
this.selectedItems = new SparseBooleanArray();
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_item, null);
}
CheckBox checkBox = view.findViewById(R.id.checkBox);
checkBox.setText(items.get(position));
checkBox.setChecked(selectedItems.get(position));
checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
selectedItems.put(position, true);
} else {
selectedItems.delete(position);
}
});
return view;
}
public SparseBooleanArray getSelectedItems() {
return selectedItems;
}
}
ListView listView = findViewById(R.id.listView);
List<String> items = Arrays.asList("Item 1", "Item 2", "Item 3", "Item 4");
CustomAdapter adapter = new CustomAdapter(this, items);
listView.setAdapter(adapter);
SparseBooleanArray selectedItems = adapter.getSelectedItems();
for (int i = 0; i < selectedItems.size(); i++) {
if (selectedItems.valueAt(i)) {
int position = selectedItems.keyAt(i);
String selectedItem = items.get(position);
Log.d("Selected Item", selectedItem);
}
}
通过以上步骤,你可以实现一个简单的多选选择框功能。你也可以根据自己的需求进行定制和扩展。