要實現多選選擇框,你可以使用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);
}
}
通過以上步驟,你可以實現一個簡單的多選選擇框功能。你也可以根據自己的需求進行定制和擴展。