在Activity/Fragment中设置搜索键的监听事件

猴子每天都要经历九九八十一难,种种bug迎风吹来。

首先设置TextView的两个属性:

(1)android:imeOptions="actionSearch"

(2)android:singleLine="true"(高版本会提示过时)或android:lines="1"

温馨提示少了第二个属性,软键盘永远不会将回车键修改为带“搜索”两字的按钮,就无法实现功能了

1、Activity中:

etSearch.setOnEditorActionListener(new EditText.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if(actionId == EditorInfo.IME_ACTION_SEARCH){
            // 先隐藏键盘
            ((InputMethodManager) etSearch.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
            Log.e("可以实现吗", "is ok ?");
            return true;
        }
        return false;
    }
});
2、Fragment中,其实就是注意一下就可以了(this\context\getactivity...):

editSearch.setOnEditorActionListener(new EditText.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if(actionId == EditorInfo.IME_ACTION_SEARCH){
            // 先隐藏键盘
            ((InputMethodManager) editSearch.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
            //获取编辑框内容,执行相应操作
            
            return true;
        }
        return false;
    }
});

3、网上说会执行两次的原因及解决:

etSearch.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        /**
         * 看情况是否需要满足其一条件
         * (keyCode == KeyEvent.KEYCODE_SEARCH) || (keyCode == KeyEvent.KEYCODE_ENTER)
         *
         * 如果少了event.getAction() == KeyEvent.ACTION_DOWN则会执行两次
         * */
        if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            //满足条件则隐藏软键盘
            ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                    getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            // TODO: 2016/9/2 具体根据按搜索键后执行的操作
            Log.e("will do twice ", "I can't believe 1");
        }
        return false;
    }
});

对于网上说不是setOnKey...而是上面匿名方法(setOnEditorActionListener),暂时没时间去研究




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值