make editText失去了对背压的关注

Ank*_*ush 23 android android-edittext

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

@Override
public void onBackPressed() {
    vibrator.vibrate(Constants.DEFAULT_VIBRATE_TIME);
    myEditText.clearFocus();
            super.onBackPressed();
}
Run Code Online (Sandbox Code Playgroud)

Kac*_*acy 18

只需扩展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 );
    }
}
Run Code Online (Sandbox Code Playgroud)

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

注意:根据您支持的最小API,您可能需要向此类添加/删除构造函数.我建议只添加它们并删除那些super()呼叫以红色加下划线的那些.

  • 完美优雅的解决方案。当您需要使用“View.OnKeyListener”使用片段覆盖后退按钮行为,并且需要在焦点窃取的 EditText 中断您的实现时捕获后退按钮单击事件时非常有用。干杯! (2认同)

rau*_*aug 3

您可以使另一个Views可聚焦,例如ImageView. 确保使其在触摸模式下可聚焦,使用setFocusableInTouchMode(true)和 ononResume()使其View变为requestFocus()

您还可以创建一个View维度为 0 的虚拟对象并执行上述相同步骤。

我希望这有帮助。