在Android中,要实现ListView的多选功能,你可以使用ListView.MultiChoiceMode
。以下是实现多选功能的步骤:
choiceMode
属性为MultiChoiceMode.MULTIPLE
或MultiChoiceMode.SINGLE
。例如:<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="multiple" />
public class MultiChoiceArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final List<String> items;
private final int resource;
public MultiChoiceArrayAdapter(Context context, int resource, List<String> items) {
super(context, resource, items);
this.context = context;
this.items = items;
this.resource = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(resource, parent, false);
viewHolder = new ViewHolder();
viewHolder.textView = convertView.findViewById(android.R.id.text1);
viewHolder.checkbox = convertView.findViewById(android.R.id.checkbox);
viewHolder.checkbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isChecked = ((CheckBox) v).isChecked();
if (isChecked) {
getSelection().add(getItem(position));
} else {
getSelection().remove(getItem(position));
}
}
});
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.textView.setText(getItem(position));
return convertView;
}
static class ViewHolder {
TextView textView;
CheckBox checkbox;
}
}
public class MainActivity extends AppCompatActivity {
private ListView listView;
private MultiChoiceArrayAdapter adapter;
private List<String> items;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
items = new ArrayList<>();
items.add("Item 1");
items.add("Item 2");
items.add("Item 3");
items.add("Item 4");
adapter = new MultiChoiceArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice, items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckBox checkBox = (CheckBox) view.findViewById(android.R.id.checkbox);
if (checkBox.isChecked()) {
// 如果复选框已选中,将其添加到已选择项目的列表中
getSelection().add(items.get(position));
} else {
// 如果复选框未选中,将其从已选择项目的列表中移除
getSelection().remove(items.get(position));
}
}
});
}
}
现在,你已经成功实现了ListView的多选功能。用户可以按住Shift键或Ctrl键(或Cmd键,适用于Mac)并单击其他列表项以选择多个项目。