使用edit text和recyclerview实现一个搜索功能
时间: 2023-05-22 14:04:34 浏览: 199
可以参考以下代码实现一个搜索功能:
首先,在布局文件中添加一个 EditText 和一个 RecyclerView:
```
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入搜索内容" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
然后,在 Activity 或 Fragment 中,初始化 EditText 和 RecyclerView,并为 EditText 添加一个 TextWatcher,用于监听 EditText 中输入的内容:
```
private EditText editText;
private RecyclerView recyclerView;
private List<String> dataList = new ArrayList<>();
private List<String> filteredList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
recyclerView = findViewById(R.id.recyclerView);
// 初始化数据
for (int i = 0; i < 100; i++) {
dataList.add("item " + i);
}
// 设置 RecyclerView 的布局管理器和适配器
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new MyAdapter(dataList));
// 监听 EditText 中输入的内容
editText.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) {
// 根据输入的内容过滤列表
filteredList.clear();
for (String item : dataList) {
if (item.contains(s.toString())) {
filteredList.add(item);
}
}
// 更新适配器中的数据
((MyAdapter) recyclerView.getAdapter()).setData(filteredList);
}
@Override
public void afterTextChanged(Editable s) {}
});
}
```
最后,实现一个适配器用于展示搜索结果:
```
private static class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private List<String> data;
public MyAdapter(List<String> data) {
this.data = data;
}
public void setData(List<String> data) {
this.data = data;
notifyDataSetChanged();
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MyViewHolder(LayoutInflater.from(parent.getContext())
.inflate(android.R.layout.simple_list_item_1, parent, false));
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.textView.setText(data.get(position));
}
@Override
public int getItemCount() {
return data.size();
}
}
private static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView textView;
public MyViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(android.R.id.text1);
}
}
```
这样,就可以实现一个基础的搜索功能了。
阅读全文