android studio Spinner下拉菜单多选源码实现
时间: 2023-07-07 09:45:40 浏览: 141
Spinner控件本身不支持多选功能,但可以通过自定义适配器来实现多选下拉菜单。
以下是一个示例代码:
```java
public class MultiSpinnerAdapter extends ArrayAdapter<String> implements OnItemClickListener {
private List<String> items;
private boolean[] selected;
private Spinner spinner;
public MultiSpinnerAdapter(Context context, int textViewResourceId, List<String> items, Spinner spinner) {
super(context, textViewResourceId, items);
this.items = items;
this.selected = new boolean[items.size()];
this.spinner = spinner;
spinner.setOnItemClickListener(this);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view.findViewById(android.R.id.text1);
if (selected[position]) {
textView.setTextColor(Color.RED);
} else {
textView.setTextColor(Color.BLACK);
}
return view;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selected[position] = !selected[position];
getView(position, view, parent);
}
public List<String> getSelectedItems() {
List<String> selectedItems = new ArrayList<>();
for (int i = 0; i < items.size(); i++) {
if (selected[i]) {
selectedItems.add(items.get(i));
}
}
return selectedItems;
}
}
```
在Activity中使用该适配器:
```java
Spinner spinner = (Spinner) findViewById(R.id.spinner);
List<String> items = Arrays.asList("Item 1", "Item 2", "Item 3", "Item 4");
MultiSpinnerAdapter adapter = new MultiSpinnerAdapter(this, android.R.layout.simple_spinner_item, items, spinner);
spinner.setAdapter(adapter);
// 获取选中的项
List<String> selectedItems = adapter.getSelectedItems();
```
以上代码实现了一个多选下拉菜单,当用户点击列表项时,会切换该项的选中状态,并且选中状态的文本颜色将变为红色。getSelectedItems()方法可以获取选中的项。
阅读全文