android开发:EditText关联软键盘enter变搜索

问题:

大概是下图这样一个页面,搜索框这里想点击就搜索,没有其他的按钮(比如:搜索按钮,完成按钮)支持,那么就只能动动输入法的脑筋了。

分析:

这个搜索框的示例,其实ios上比较流行且统一(毕竟就苹果家自己的,想做什么样都可以,安卓碎片化 emmmm),就想起来安卓其实也有这种功能,说做就做!

相关资料

首先既然想在EditText 获取焦点以后,键盘右下角显示完成,那就在需在xml文件中为EditText添加android:imeOptions=”actionSend”属性

EditText对外提供了androidimeOptions属性,控制该按钮的显示文字

imeOptions   文字
actionGo 开始
actionNext  下一步
actionSearch 搜索
actionSend  发送
actionDone  Enter符号 

 要使android:imeOptions起作用,必须能加上android:inputType属性,这也是一开始强调的 或者加上android:singleLine=”true”也可以,但是用android:maxLines=”1”不可以。

解决:

根据以上资料,我们把输入框EditText的android:imeOptions=”actionSearch”,然后增加搜索按钮的点击监听即可:

EditText

<EditText
        android:id = "@+id/edt_input_search"
        android:layout_width = "match_parent"
        android:layout_height = "26dp"
        android:layout_marginTop = "11dp"
        android:layout_marginLeft = "14dp"
        android:layout_marginRight = "14dp"
        android:paddingLeft = "8dp"
        android:paddingRight = "12dp"
        android:background = "@drawable/shape_solid_white_corner20"
        android:drawableLeft = "@mipmap/icon_search"
        android:drawablePadding = "6dp"
        android:gravity = "center_vertical"
        android:maxLength = "30"
//增加单行显示标记
        android:singleLine = "true"
//增加键盘按钮改搜索字样
        android:imeOptions="actionSearch"
        android:textSize = "11dp"/>

activity的editText关联软键盘搜索按钮的点击监听:

 edtInputSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                boolean handled = false;
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //开始搜索
                    handled = true;

                    /*隐藏软键盘*/
                    InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(
                        Context.INPUT_METHOD_SERVICE);
                    if (inputMethodManager.isActive()) {
                        inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
                    }
                    String searchContent = v.getText().toString().trim();
                    LogTag.d("输入:"+searchContent);
                }
                return handled;
            }
        });

效果:

效果当然就是打印log,软键盘下去啦!

结语:

效果比较简单,就不贴效果了,咱们开发时要记住有这个功能tips,避免产品要出这种需求时,打我们一个措手不及,还有,要坚持一点,功能可以做,但是样式没法统一(这个必须和产品讲明白,不然测试。。。),因为咱们可见的安卓手机产品就包括 华为,小米,魅族,三星,,,各家有各家的想法,效果也就不一样了(算了,华为一通天下吧)

发布了58 篇原创文章 · 获赞 10 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_34203714/article/details/101308199