Android SearchView设置与用法的那点事儿


// 设置该SearchView默认是否自动缩小为图标
mSearchView.setIconifiedByDefault(false);
// 为该SearchView组件设置事件监听器
mSearchView.setOnQueryTextListener(this);
// 设置该SearchView显示确认搜索按钮
mSearchView.setSubmitButtonEnabled(true);
// 设置该SearchView内默认显示的提示文本
mSearchView.setQueryHint("查找");
//设置
mSearchView.setIconified(false);
//清除焦点
mSearchView.clearFocus();
//获取焦点
mSearchView.requestFocus();

EditText默认自动获取焦点的,会弹出软键盘

下面是关闭SearchView自动获取焦点的代码

<span style="font-size:14px;"><span style="font-size:14px;"> <LinearLayout
            android:id="@+id/focus"
            android:layout_width="fill_parent"
            android:layout_height="60dp"
            android:background="#EAEAEA"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:gravity="center_vertical"
            android:orientation="horizontal" >

            <SearchView
                android:id="@+id/searchView"
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:layout_marginRight="20dp"
                android:gravity="left|center_vertical"
                android:iconifiedByDefault="false"
                android:inputType="textFilter"
                android:queryHint="输入IP"
                android:textColor="#ABABAB"
                android:textColorHint="#ABABAB" />

 </LinearLayout></span></span>

只需要在SearchView的父级控件中添加以下属性:

<span style="font-size:14px;"><span style="font-size:14px;">android:focusable="true"
android:focusableInTouchMode="true"</span></span>

就在进入的时候不会自动获取焦点

但是当你点击SearchView获取焦点后,到别的activity再回来的时候,失效了,总是自动获取焦点并且弹出软键盘

这里有个办法就是在onResume方法里添加以下代码

<span style="font-size:14px;"><span style="font-size:14px;">@Override
protected void onResume() {
super.onResume();
mSearchView.setFocusable(true);
mSearchView.setFocusableInTouchMode(true);
//mSearchView.requestFocus();  //获取焦点
}</span></span>

回到这个activity会执行onResume方法,让它执行上面的代码,就不再会自动获取焦点了。

关注公众号,分享干货,讨论技术



原文地址:https://www.cnblogs.com/molashaonian/p/9097669.html