先来个图:
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > <ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> </LinearLayout> |
search_menu.xml
1 2 3 4 5 6 7 8 9 10 11 12 |
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/search" android:title="@string/search_label" android:icon="@android:drawable/ic_menu_search" android:showAsAction="ifRoom|collapseActionView" android:actionViewClass="android.widget.SearchView"> </item> </menu> |
MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
package com.dave.searchviewdemo; import android.app.Activity; import android.os.Bundle; import android.text.TextUtils; import android.view.Menu; import android.view.Window; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.SearchView; import android.widget.SearchView.OnQueryTextListener; public class MainActivity extends Activity implements OnQueryTextListener{ private static final String TAG = MainActivity.class.getSimpleName(); private ListView mListView; private SearchView mSearchView; private String[] mWords ={"hello","how","who","iphone","android","when","where"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); setContentView(R.layout.activity_main); mListView = (ListView) findViewById(R.id.list_view); mListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mWords)); // 启用文本过滤 mListView.setTextFilterEnabled(true); } private void setupSearchView() { mSearchView.setIconifiedByDefault(true); mSearchView.setOnQueryTextListener(this); mSearchView.setQueryHint("Search words..."); mSearchView.setSubmitButtonEnabled(false); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.search_menu, menu); mSearchView = (SearchView) menu.findItem(R.id.search).getActionView(); setupSearchView(); return super.onCreateOptionsMenu(menu); } @Override public boolean onQueryTextChange(String queryText) { // 花样儿其实就在这儿 if(TextUtils.isEmpty(queryText)){ mListView.clearTextFilter(); }else{ mListView.setFilterText(queryText); } return true; } @Override public boolean onQueryTextSubmit(String queryText) { return false; } } |
声明:eoe文章著作权属于作者,受法律保护,转载时请务必以超链接形式附带如下信息
原文作者: