要在Android Spinner中實現搜索功能,可以通過以下幾個步驟:
以下是一個簡單的示例代碼:
public class MainActivity extends AppCompatActivity {
private Spinner mSpinner;
private EditText mEditText;
private ArrayAdapter<String> mAdapter;
private List<String> mDataList;
private List<String> mFilteredDataList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSpinner = findViewById(R.id.spinner);
mEditText = findViewById(R.id.editText);
mDataList = Arrays.asList(getResources().getStringArray(R.array.data_list));
mFilteredDataList = new ArrayList<>(mDataList);
mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, mFilteredDataList);
mSpinner.setAdapter(mAdapter);
mEditText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String filterKeyword = s.toString().toLowerCase();
mFilteredDataList.clear();
for (String data : mDataList) {
if (data.toLowerCase().contains(filterKeyword)) {
mFilteredDataList.add(data);
}
}
mAdapter.notifyDataSetChanged();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
}
在這個示例中,我們創建了一個Spinner和一個EditText,通過監聽EditText的文本變化事件,在Adapter中實現數據過濾功能,通過更新Adapter的數據展示來實現Spinner的搜索功能。