其实实现ListView过滤功能最方便的便是使用ArrayAdapter,里面自带的 getFilter()方法能很方便的实现此功能,但是在实际的开发中,一般都是继承于 BaseAdapter。还有一种是利用控件AutoComplete,这种方式只是在输入框的下方 重新显示一个列表,显然,很多时候这两种方式也满足不了我们的要求。
在Activity中定义一个类,让它实现TextWatcher接口,然后再onTextChanged 方法中去过滤。然后常见相应的Pattern和match,来判断传入的参数时候符合列表 中的数据,符合就加入一个新的列表中。
首先贴出实现的效果图
下面贴出主要实现代码
package com.example.demo; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.os.Bundle; import android.app.Activity; import android.text.Editable; import android.text.TextWatcher; import android.view.Menu; import android.widget.EditText; import android.widget.ListView; public class MainActivity extends Activity { List<People> people = new ArrayList<People>() ; EditText editinput; ListView listview; Adapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editinput = (EditText)findViewById(R.id.edit); listview = (ListView)findViewById(R.id.ydlist); initdata(); adapter = new Adapter(getApplicationContext(), people); listview.setAdapter(adapter); editinput.addTextChangedListener(new watcher()); } void initdata(){ people.add(new People("张三","1374456")); people.add(new People("张三小子", "12444455")); people.add(new People("李一", "1345555")); people.add(new People("王一", "1355555")); people.add(new People("王二", "1365555")); people.add(new People("李三", "13565555")); people.add(new People("李一", "123555")); } class watcher implements TextWatcher{ @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub String aa = s.toString(); Pattern p = Pattern.compile(aa); List<People> we = new ArrayList<People>(); for(int i=0;i<people.size();i++){ People pp = people.get(i); Matcher matcher = p.matcher(pp.getName()+pp.getPhome()); if(matcher.find()){ we.add(pp); } } adapter = new Adapter(getApplicationContext(), we); listview.setAdapter(adapter); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索android
, listview
, textwatcher
, android adapter
, android listview
, new
, android edittext
, android 过滤
, import
, listview adapter
, override
, listview+edittext
, baseadapter
, android listview
arrayadapter
listview baseadapter、继承arrayadapter、继承baseadapter、listview adapter、listview.setadapter,以便于您获取更多的相关知识。