Android SearchView详细使用
布局
<RelativeLayout
android:id="@+id/activity_main_testlayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp">
<android.support.v7.widget.SearchView
android:id="@+id/activity_main_test_searchview"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_margin="10dp"
android:background="@drawable/search_selector"
android:queryHint="请输入物品名称">
</android.support.v7.widget.SearchView>
</RelativeLayout>
SearchView一些常用的属性
android:iconifiedByDefault:设置搜索图标是否显示在搜索框内(相关的方法setIconifiedByDefault(boolean))。
android:imeOptions:设置输入法搜索选项字段,默认是搜索,可以是:下一页、发送、完成等(相关的方法setImeOptions(int))。
android:inputType:设置输入类型(相关的方法setInputType(int))。
android:maxWidth:设置最大宽度(相关的方法setMaxWidth(int))。
android:queryHint:设置查询提示字符串(相关的方法setQueryHint(CharSequence))。
Java代码
/**
* Android SearchView
* */
private void initSearchView() {
SearchView searchView = findViewById(R.id.activity_main_test_searchview);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//输入完成后,提交时触发的方法,一般情况是点击输入法中的搜索按钮才会触发,表示现在正式提交了
public boolean onQueryTextSubmit(String query) {
if (TextUtils.isEmpty(query)) {
Toast.makeText(MainActivity.this, "请输入查找内容111!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, query, Toast.LENGTH_SHORT).show();
}
return true;
}
//在输入时触发的方法,当字符真正显示到searchView中才触发,像是拼音,在输入法组词的时候不会触发
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
Toast.makeText(MainActivity.this, "请输入查找内容222!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, newText, Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
注意是android.support.v7.widget.SearchView包 而不是android.widget.SearchView包