SearchView是Android原生的搜索框控件,它提供了一個用戶界面,能夠讓用戶在文本框內輸入文字,並容許經過看監聽器監控用戶輸入,當用戶輸入完成後提交搜索時,也可經過監聽器執行實際的搜索。android
SearchView屬性以下:ide
XML屬性佈局 |
相關方法this |
說明spa |
Android:IconifiedByDefault(Boolean iconified)code |
setIconifiedByDefault(boolean)xml |
設置該搜索框默認是否自動縮小爲圖標blog |
android:imeOptions事件 |
setImeOptions(int)utf-8 |
設置輸入法搜索選項字段,默認是搜索,能夠是:下一頁、發送、完成等 |
android:inputType |
setInputType(int) |
設置輸入類型 |
android:maxWidth |
setMaxWidth(int) |
設置最大寬度 |
android:queryHint |
setQueryHint(CharSequence) |
設置查詢提示字符串 |
使用SearchView時可以使用以下經常使用方法。
setIconifiedByDefault(Boolean iconified):設置該搜索框默認是否自動縮小爲圖標。
setSubmitButtonEnabled(Boolean enabled):設置是否顯示搜索按鈕。
setQueryHint(CharSequence hint):設置搜索框內默認顯示的提示文本。
setOnQueryTextListener(SearchView.OnQueryTextListener listener):爲該搜索框設置事件監聽器。
若是爲SearchView增長一個配套的ListView,則能夠爲SearchView增長自動完成功能。下面實例示範如何使用SearchView。
佈局文件以下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
<!--定義一個SearchView-->
<SearchView android:id="@+id/searchview" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<!--爲SearchView定義自動完成的ListView-->
<ListView android:id="@+id/listview" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/>
</LinearLayout>
主程序以下:
public class MainActivity extends AppCompatActivity { private String[] mStrings = new String[]{"說好不哭", "等你下課", "不愛我就拉到", "123456"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ListView listView = findViewById(R.id.listview); listView.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, mStrings)); //設置ListView啓用過濾 listView.setTextFilterEnabled(true); SearchView searchView = findViewById(R.id.searchview); //設置該SearchView默認是否自動縮小爲圖標 searchView.setIconifiedByDefault(false); //設置該SearchView顯示搜索按鈕 searchView.setSubmitButtonEnabled(true); searchView.setQueryHint("查找"); //爲該SearchView組件設置事件監聽器 searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { //單機搜索按鈕時激發該方法 @Override public boolean onQueryTextSubmit(String query) { //實際應用中應該在該方法內執行實際查詢,此處僅使用Toast顯示用戶輸入的查詢內容 Toast.makeText(MainActivity.this, "你的選擇是:" + query, Toast.LENGTH_SHORT).show(); return false; } //用戶輸入字符時激發該方法 @Override public boolean onQueryTextChange(String newText) { //若是newText不是長度爲0的字符串 if (TextUtils.isEmpty(newText)) { //清除ListView的過濾 listView.clearTextFilter(); } else { //使用用戶輸入的內容對ListView的列表項進行過濾 listView.setFilterText(newText); } return true; } }); } }
本例中定義了一個ListView組件用於爲SearchView組件顯示自動完成列表。
運行結果以下: