是的,Android的Spinner可以实现自动过滤重复项。你可以通过自定义一个适配器来实现这个功能。以下是一个简单的示例:
BaseAdapter
:public class CustomSpinnerAdapter extends BaseAdapter {
private Context context;
private List<String> data;
private List<String> uniqueData;
public CustomSpinnerAdapter(Context context, List<String> data) {
this.context = context;
this.data = data;
this.uniqueData = removeDuplicates(data);
}
@Override
public int getCount() {
return uniqueData.size();
}
@Override
public Object getItem(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<String> removeDuplicates(List<String> data) {
List<String> uniqueList = new ArrayList<>();
for (String item : data) {
if (!uniqueList.contains(item)) {
uniqueList.add(item);
}
}
return uniqueList;
}
}
List<String> data = 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就会自动过滤掉重复项,只显示唯一的选项。