Android_SearchView

  • 布局文件
<RelativeLayout 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"
    >

<SearchView
    android:id="@+id/search_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:iconifiedByDefault="true"
    android:inputType="text"
    android:imeOptions="actionSearch"
    android:queryHint="搜索" />

</RelativeLayout>

重要属性如下:
android:iconifiedByDefault表示搜索图标是否在输入框内。true效果更加
android:imeOptions设置IME options,即输入法的回车键的功能,可以是搜索、下一个、发送、完成等等。这里actionSearch表示搜索
android:inputType输入框文本类型,可控制输入法键盘样式,如numberPassword即为数字密码样式android:queryHint输入框默认文本

  • 代码
 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    searchView = (SearchView) findViewById(R.id.search_view);
    searchView.setIconified(false);
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

        public boolean onQueryTextSubmit(String query) {
            Toast.makeText(MainActivity.this, "begin search", Toast.LENGTH_SHORT)
                    .show();
            return true;
        }

        public boolean onQueryTextChange(String newText) {
            if (newText != null && newText.length() > 0) {
                Log.d("", "text change");
            }
            return true;
        }
    });
    // show keyboard
    getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
                    | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}

searchView.onActionViewExpanded();表示在内容为空时不显示取消的x按钮,内容不为空时显示.
searchView.setSubmitButtonEnabled(true);编辑框后显示search按钮,建议用android:imeOptions=”actionSearch”代替。

//隐藏键盘

InputMethodManager inputMethodManager;
inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);

private void hideSoftInput() {
if (inputMethodManager != null) {
View v = SearchActivity.this.getCurrentFocus();
if (v == null) {
return;
}

inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
searchView.clearFocus();
}
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,645评论 25 708
  • 内容抽屉菜单ListViewWebViewSwitchButton按钮点赞按钮进度条TabLayout图标下拉刷新...
    皇小弟阅读 46,908评论 22 665
  • RelativeLayout 第一类:属性值为true可false android:layout_centerHr...
    兀兀沙弥阅读 3,063评论 0 15
  • 家乡有个杜甫亭我是知道的,前几年去拜佛时误打误撞进去过,也是因缘际会。原本那是有个怀甫风景区的,大概是因为景物不多...
    忆言如晤阅读 335评论 0 1
  • 黄堡文化研究 第192期作者:李月芳编辑:秦陇华 春来原上涌花潮,款款佳丽似桃夭。山色空濛新如洗,田园犹润昨夜雨...
    primates阅读 809评论 0 0