Android學習------運用 Filter 實現關鍵字搜尋,並且高亮顯示關鍵字
阿新 • • 發佈:2019-02-05
新鮮出爐的demo 程式碼有點亂 講究著看吧。。。頭暈。。
先看 想要實現的功能效果 :
第一步 資料初始化
第二步監聽 輸入框裡面的 關鍵字 進行過濾 運用Filter 過濾
第三步 在自己的adapter類裡面實現自己的 Filterable 介面 重寫 getFilter()方法 返回自己的Filter物件
第四步 建立自己的Filter物件 並且在 performFiltering 方法裡面實現你的過濾規則 完成以後返回filterResults 物件 publishResults 方法會接受到 performFiltering 方法返回的物件 然後更新listView 即可。
第五步 看程式碼
這裡我使用了SearchView 用EdittextView 也可以。
先看MainActivity
上面的程式碼沒啥好說的感覺 ,只是別忘記設定 listv.setTextFilterEnabled(true);public class MainActivity extends Activity { SearchView searchview; List<String> list = new ArrayList<String>(); private SearchView.SearchAutoComplete edit; ListView listv; MyAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initData(); initView(); } private void initView() { // TODO Auto-generated method stub searchview = (SearchView) findViewById(R.id.searchview); listv = (ListView) findViewById(R.id.listv); adapter = new MyAdapter<String>(this, list); listv.setAdapter(adapter); listv.setTextFilterEnabled(true); searchview.setQueryHint("請輸入你要查詢的關鍵字"); searchview.setIconified(false); searchview.setIconifiedByDefault(false); searchview.setOnQueryTextListener(new OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String arg0) { // TODO Auto-generated method stub return false; } @Override public boolean onQueryTextChange(String queryText) { if (TextUtils.isEmpty(queryText)) { adapter.getFilter().filter(null); } else { adapter.getFilter().filter(queryText); } return true; } }); } private void initData() { // TODO Auto-generated method stub list.add("張三"); list.add("李思"); list.add("王麻子"); list.add("張三"); list.add("aaaa"); list.add("cccc"); list.add("dd"); list.add("qwe三"); list.add("2444"); list.add("vvvv"); list.add("55522"); list.add("667732f"); }
public class MyAdapter<T> extends BaseAdapter implements Filterable { private Context context; private ArrayList<T> mOriginalValues; private List<T> mObjects; private final Object mLock = new Object(); private LayoutInflater mInflater; private String keyWrold = ""; // 關鍵字 public MyAdapter(Context context, List<T> list) { this.context = context; this.mObjects = list; this.mInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // TODO Auto-generated method stub if (mObjects == null || mObjects.size() == 0) return 0; return mObjects.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ViewHolder viewHolder; if (convertView == null) { convertView = mInflater.inflate(R.layout.item, parent, false); viewHolder = new ViewHolder(); viewHolder.txtv = (TextView) convertView.findViewById(R.id.txtv); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } String str = mObjects.get(position).toString().toLowerCase(); if (!keyWrold.equals("")) { String patten = "" + keyWrold; Pattern p = Pattern.compile(patten); Matcher m = p.matcher(str); SpannableString spannableString = new SpannableString(str); while (m.find()) { if (str.contains(m.group())) { spannableString.setSpan( new ForegroundColorSpan(0xffec8b44), m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } viewHolder.txtv.setText(spannableString); } else { SpannableString spannableString = new SpannableString(str); spannableString.setSpan(new ForegroundColorSpan(Color.BLACK), 0, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); viewHolder.txtv.setText(mObjects.get(position).toString()); } return convertView; } class ViewHolder { TextView txtv; } @Override public Filter getFilter() { // TODO Auto-generated method stub return filter; } Filter filter = new Filter() { @Override protected void publishResults(CharSequence constraint, FilterResults results) { mObjects = (List<T>) results.values; if (results.count > 0) { notifyDataSetChanged(); } else { notifyDataSetInvalidated(); } } @Override protected FilterResults performFiltering(CharSequence prefix) { // TODO Auto-generated method stub FilterResults filterResults = new FilterResults(); if (mOriginalValues == null) { synchronized (mLock) { mOriginalValues = new ArrayList<T>(mObjects); } } if (prefix == null || prefix.length() == 0) { ArrayList<T> list; synchronized (mLock) { list = new ArrayList<T>(mOriginalValues); } filterResults.values = list; filterResults.count = list.size(); keyWrold = ""; } else { String prefixString = prefix.toString().toLowerCase(); ArrayList<T> values; synchronized (mLock) { values = new ArrayList<T>(mOriginalValues); } final int count = values.size(); final ArrayList<T> newValues = new ArrayList<T>(); for (int i = 0; i < count; i++) { final T value = values.get(i); final String valueText = value.toString().toLowerCase(); // First match against the whole, non-splitted value if (valueText.contains(prefixString)) { newValues.add(value); keyWrold = prefixString; } } filterResults.values = newValues; filterResults.count = newValues.size(); } return filterResults; } }; }
建立一個自己的filter物件 實現自己的過濾規則 最後在publishResults方法裡面更新listview , 如果需要給關鍵字加深顏色 注意看 getView keyWrold 的處理
湊合著看吧,有問題還望指出。