是的,Android的Spinner可以实现自动过滤重复项。你可以通过自定义一个适配器来实现这个功能。以下是一个简单的示例:
- 首先,创建一个自定义的适配器,继承自
BaseAdapter
:
public class CustomSpinnerAdapter extends BaseAdapter { private Context context; private Listdata; private List uniqueData; public CustomSpinnerAdapter(Context context, List data) { this.context = context; this.data = https://www.yisu.com/ask/data;"hljs">int position) { return uniqueData.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(android.R.layout.simple_spinner_item, parent, false); } TextView textView = convertView.findViewById(android.R.id.text1); textView.setText(uniqueData.get(position)); return convertView; } private List removeDuplicates(List data) { List uniqueList = new ArrayList<>(); for (String item : data) { if (!uniqueList.contains(item)) { uniqueList.add(item); } } return uniqueList; } }
- 在你的Activity或Fragment中,使用这个自定义适配器为Spinner设置数据:
Listdata = https://www.yisu.com/ask/new ArrayList<>(); data.add("Item 1"); data.add("Item 2"); data.add("Item 1"); data.add("Item 3"); data.add("Item 2"); CustomSpinnerAdapter adapter = new CustomSpinnerAdapter(this, data); Spinner spinner = findViewById(R.id.spinner); spinner.setAdapter(adapter);
这样,Spinner就会自动过滤掉重复项,只显示唯一的选项。