,可以通过以下步骤来实现:
<com.example.searchablespinner.SearchableSpinner
android:id="@+id/searchableSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Select an item"
android:background="@drawable/rounded_corner_background" />
public class CustomAdapter extends ArrayAdapter<String> {
private Context context;
private List<String> itemList;
public CustomAdapter(Context context, List<String> itemList) {
super(context, R.layout.custom_spinner_item, itemList);
this.context = context;
this.itemList = itemList;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_spinner_item, parent, false);
TextView textView = view.findViewById(R.id.spinnerItemText);
textView.setText(itemList.get(position));
return view;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_spinner_dropdown_item, parent, false);
TextView textView = view.findViewById(R.id.spinnerDropdownItemText);
textView.setText(itemList.get(position));
return view;
}
}
SearchableSpinner searchableSpinner = findViewById(R.id.searchableSpinner);
List<String> itemList = new ArrayList<>();
itemList.add("Item 1");
itemList.add("Item 2");
itemList.add("Item 3");
CustomAdapter adapter = new CustomAdapter(this, itemList);
searchableSpinner.setAdapter(adapter);
Filter filter = adapter.getFilter();
searchableSpinner.getEditText().addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
filter.filter(s);
}
@Override
public void afterTextChanged(Editable s) {
}
});
searchableSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = (String) parent.getItemAtPosition(position);
Toast.makeText(MainActivity.this, "Selected item: " + selectedItem, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
这样就可以在安卓系统中使用带自定义适配器的SearchableSpinner了。
相关链接:
领取专属 10元无门槛券
手把手带您无忧上云