在Android中,為Spinner實現選項過濾功能可以通過以下步驟來完成:
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
List<String> spinnerItems = new ArrayList<>();
spinnerItems.add("選項1");
spinnerItems.add("選項2");
spinnerItems.add("選項3");
// ... 添加更多選項
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, spinnerItems);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = findViewById(R.id.spinner);
spinner.setAdapter(spinnerAdapter);
<EditText
android:id="@+id/search_box"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="搜索選項" />
EditText searchBox = findViewById(R.id.search_box);
searchBox.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) {
filterSpinnerOptions(s.toString());
}
@Override
public void afterTextChanged(Editable s) {
}
});
filterSpinnerOptions
方法,該方法將根據用戶輸入過濾Spinner選項。例如:private void filterSpinnerOptions(String searchText) {
List<String> filteredItems = new ArrayList<>();
for (String item : spinnerItems) {
if (item.toLowerCase().contains(searchText.toLowerCase())) {
filteredItems.add(item);
}
}
ArrayAdapter<String> filteredAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, filteredItems);
filteredAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(filteredAdapter);
}
現在,當用戶在搜索框中輸入文本時,Spinner的選項將根據輸入的文本進行過濾。