使editText失去对新闻的关注
在我的活动中,我有一个editText字段。 当用户点击它时,editText获得焦点并出现键盘。 现在,当用户按下手机上的硬件返回按钮时,键盘消失,但光标保持在编辑文本中,即它仍然具有焦点。 按下后退按钮时是否可以使EditText失去焦点? 我尝试使用下面的代码,但它不起作用:
@Override
public void onBackPressed() {
    vibrator.vibrate(Constants.DEFAULT_VIBRATE_TIME);
    myEditText.clearFocus();
            super.onBackPressed();
}
只需扩展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> 。 
  注意:您可能需要根据您支持的最小API向该类添加/删除构造函数。  我建议把它们全部加入,并删除super()调用以红色标出的那些。 
  您可以制作另一个可调焦的Views ,例如ImageView 。  一定要使它在触摸模式下可聚焦,使用setFocusableInTouchMode(true)和onResume()将该View为requestFocus() 。 
  您也可以创建一个具有0维的虚拟View ,并执行上述相同的步骤。 
我希望这有帮助。
添加比EditText更高的视图:
<LinearLayout
    android:layout_width="0px"
    android:layout_height="0px"
    android:focusable="true"
    android:focusableInTouchMode="true" />
也要隐藏键盘在onBackPressed()中添加此项:
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
上一篇: make editText lose focus on back press
下一篇: EditText has focus when Activity starts, but soft keyboard is not shown
