是的,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就會自動過濾掉重復項,只顯示唯一的選項。