要在Android Spinner中實(shí)現(xiàn)搜索功能,可以通過以下幾個(gè)步驟:
以下是一個(gè)簡單的示例代碼:
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) {
}
});
}
}
在這個(gè)示例中,我們創(chuàng)建了一個(gè)Spinner和一個(gè)EditText,通過監(jiān)聽EditText的文本變化事件,在Adapter中實(shí)現(xiàn)數(shù)據(jù)過濾功能,通過更新Adapter的數(shù)據(jù)展示來實(shí)現(xiàn)Spinner的搜索功能。