使editText失去对后按的关注 [英] make editText lose focus on back press

查看:48
本文介绍了使editText失去对后按的关注的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的活动中,我有一个editText字段.当用户点击它时,editText将获得焦点并出现键盘.现在,当用户按下电话上的硬件后退按钮时,键盘消失,但光标仍保留在Edittext中,即.例如,它仍然具有焦点.按下后退按钮时,是否有可能使EditText失去焦点?我尝试使用以下代码,但没有用:

In my activity, I have a editText field. When the user taps on it, the editText gains the focus and the keyboard appears. Now, when the user presses the hardware back button on the phone, the keyboard disappears but the cursor remains in the Edittext, i. e., it still has the focus. Is it possible to make the EditText lose focus when back button is pressed? I tried using the following code but it didn't work:

@Override
public void onBackPressed() {
    vibrator.vibrate(Constants.DEFAULT_VIBRATE_TIME);
    myEditText.clearFocus();
            super.onBackPressed();
}

推荐答案

只需扩展EditText:

Just extend EditText:

public class EditTextV2 extends EditText
{
    public EditTextV2( Context context )
    {
        super( context );
    }

    public EditTextV2( Context context, AttributeSet attribute_set )
    {
        super( context, attribute_set );
    }

    public EditTextV2( Context context, AttributeSet attribute_set, int def_style_attribute )
    {
        super( context, attribute_set, def_style_attribute );
    }

    @Override
    public boolean onKeyPreIme( int key_code, KeyEvent event )
    {
        if ( event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP )
            this.clearFocus();

        return super.onKeyPreIme( key_code, event );
    }
}

在xml中,只需使用<yourPackage.EditTextV2>而不是<EditText>.

And in the xml just use <yourPackage.EditTextV2> instead of <EditText>.

注意:您可能需要根据所支持的最小API向此类添加/删除构造函数.我建议只添加所有这些内容,并删除其super()调用以红色下划线标出的内容.

Note: You may need to add/remove constructors to this class depending on the min API you're supporting. I suggest just adding them all and removing the ones whose super() calls get underlined in red.

这篇关于使editText失去对后按的关注的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆