這期內容當中小編將會給大家帶來有關Android應用中SearchView屬性的作用有哪些,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
SearchView是搜索框組件,它可以讓用戶在文本框里輸入文字,通過監聽器取得用戶的輸入,當用戶點擊搜索時,監聽器執行實際的搜索。
1、SearchView組件的常用方法如下:
①setIconifiedByDefault(boolean iconified) ===> 設置搜索框默認是否自動縮小為圖標。
②setOnQueryTextListener(SearchView,OnQueryTextListener listener) ===> 為搜索框設置監聽器
③setSubmitButtonEnabled(boolean enabled) ===> 設置是否顯示搜索按鈕
④setQueryHint(CharSequence hint) ===> 設置搜索框內的默認顯示的提示文本
2、為SearchView增加一個配套的ListView,則可以為其增加自動完成的功能,即ListView用于為SearchView顯示自動補齊列表
3、具體實現代碼如下:
html
<?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/sv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<!-- 為SearchView定義自動補齊的ListView-->
<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
java
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import android.app.Activity;
public class SearchViewTest extends Activity implements
SearchView.OnQueryTextListener {
private SearchView sv;
private ListView lv;
// 自動完成的列表
private final String[] mStrings = { "aaaaa", "bbbbbb", "cccccc", "ddddddd" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView) findViewById(R.id.lv);
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, mStrings));
lv.setTextFilterEnabled(true);//設置lv可以被過慮
sv = (SearchView) findViewById(R.id.sv);
// 設置該SearchView默認是否自動縮小為圖標
sv.setIconifiedByDefault(false);
// 為該SearchView組件設置事件監聽器
sv.setOnQueryTextListener(this);
// 設置該SearchView顯示搜索按鈕
sv.setSubmitButtonEnabled(true);
// 設置該SearchView內默認顯示的提示文本
sv.setQueryHint("查找");
}
// 用戶輸入字符時激發該方法
@Override
public boolean onQueryTextChange(String newText) {
Toast.makeText(SearchViewTest.this, "textChange--->" + newText, 1).show();
if (TextUtils.isEmpty(newText)) {
// 清除ListView的過濾
lv.clearTextFilter();
} else {
// 使用用戶輸入的內容對ListView的列表項進行過濾
lv.setFilterText(newText);
}
return true;
}
// 單擊搜索按鈕時激發該方法
@Override
public boolean onQueryTextSubmit(String query) {
// 實際應用中應該在該方法內執行實際查詢
// 此處僅使用Toast顯示用戶輸入的查詢內容
Toast.makeText(this, "您的選擇是:" + query, Toast.LENGTH_SHORT).show();
return false;
}
} 上述就是小編為大家分享的Android應用中SearchView屬性的作用有哪些了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。