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()
呼叫以红色加下划线的那些.
您可以使另一个Views
可聚焦,例如ImageView
. 确保使其在触摸模式下可聚焦,使用setFocusableInTouchMode(true)
和 ononResume()
使其View
变为requestFocus()
。
您还可以创建一个View
维度为 0 的虚拟对象并执行上述相同步骤。
我希望这有帮助。
归档时间: |
|
查看次数: |
12050 次 |
最近记录: |