edittext展示listview
时间: 2023-07-29 12:07:35 浏览: 108
要实现在 EditText 中输入内容并展示 ListView 的效果,可以按照以下步骤:
1. 在布局文件中添加一个 EditText 和一个 ListView。
2. 创建一个适配器 Adapter,将数据和布局文件绑定。
3. 在 Activity 中获取 EditText 和 ListView 的实例,并为 EditText 添加文本改变监听器。
4. 在文本改变监听器中获取 EditText 的内容,并根据内容过滤数据源。
5. 将过滤后的数据源更新到适配器中,并调用适配器的 notifyDataSetChanged() 方法刷新 ListView。
以下是代码示例:
布局文件:
```
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/et_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search..."/>
<ListView
android:id="@+id/lv_search_result"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
```
Adapter:
```
public class MyAdapter extends BaseAdapter {
private List<String> mData;
private LayoutInflater mInflater;
public MyAdapter(Context context, List<String> data) {
mData = data;
mInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return mData.size();
}
@Override
public String getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_listview, parent, false);
}
TextView tv = convertView.findViewById(R.id.tv_item);
tv.setText(getItem(position));
return convertView;
}
}
```
Activity:
```
public class MainActivity extends AppCompatActivity {
private EditText mEtSearch;
private ListView mLvSearchResult;
private List<String> mData;
private MyAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEtSearch = findViewById(R.id.et_search);
mLvSearchResult = findViewById(R.id.lv_search_result);
mData = new ArrayList<>(Arrays.asList("Apple", "Banana", "Cherry", "Durian", "Elderberry"));
mAdapter = new MyAdapter(this, mData);
mLvSearchResult.setAdapter(mAdapter);
mEtSearch.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) {
String keyword = s.toString().toLowerCase(Locale.getDefault());
List<String> filteredData = new ArrayList<>();
for (String item : mData) {
if (item.toLowerCase(Locale.getDefault()).contains(keyword)) {
filteredData.add(item);
}
}
mAdapter = new MyAdapter(MainActivity.this, filteredData);
mLvSearchResult.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
@Override
public void afterTextChanged(Editable s) {}
});
}
}
```
阅读全文