我希望能够从EditText删除焦点。例如,如果键盘出现,用户用后退按钮隐藏它,我希望焦点和光标消失。怎样才能做到呢?
当前回答
将这两个属性添加到你的父布局(例如:线性布局,相对布局)
android:focusable="true"
android:focusableInTouchMode="true"
它会成功的:)
其他回答
check your xml file
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp" >
**<requestFocus />**
</EditText>
//Remove **<requestFocus />** from xml
在评论中,你问是否可以聚焦另一个视图而不是EditText。是的,它可以。使用.requestFocus()方法用于你想在开始时聚焦的视图(在onCreate()方法中)
同样聚焦其他视图也会减少一些代码。(例如隐藏键盘的代码)
我也有同样的问题。这简直让我疯了。
我有一个扩展的对话框与一个ScrollView,它有一个表布局与扩展的线性布局,其中包含一个搜索栏和一个编辑文本。
第一个EditText在显示对话框后总是自动对焦,在完成键盘上的文本编辑后,EditText仍然有焦点,键盘仍然可见。
我几乎尝试了这个线程的所有解决方案,没有一个对我有效。
所以这里我的简单解决方案:(text = EditText)
text.setOnEditorActionListener( new OnEditorActionListener( ){
public boolean onEditorAction( TextView v, int actionId, KeyEvent event ){
if( (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) ||
(actionId == EditorInfo.IME_ACTION_DONE) ){
text.clearFocus( );
InputMethodManager iMgr = null;
iMgr = (InputMethodManager)mContext.getSystemService( Context.INPUT_METHOD_SERVICE );
iMgr.hideSoftInputFromWindow( text.getWindowToken(), 0 );
}
return true;
}
});
顺便说一下,我没有使用以下任何片段来解决它:
//setFocusableInTouchMode( true )
//setFocusable( true )
//setDescendantFocusability( ViewGroup.FOCUS_BEFORE_DESCENDANTS )
而且我没有使用像宽高为1dp的视图这样的间隔项。
希望它能帮助到某人:D
你可以通过设置父元素的属性android:descendantFocusability来避免对元素的任何关注。
这里有一个例子:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/search__scroller"
android:descendantFocusability="blocksDescendants"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ScrollView>
在这里,属性android:descendantFocusability设置为“blocksDescendants”是阻止对子元素的关注。
你可以在这里找到更多信息。
当活动开始时隐藏键盘。在onCreate()中编写以下代码..
InputMethodManager imm = (InputMethodManager)
getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
清除焦点并从edittext.....中删除光标
editText.clearFocus();
editText.setCursorVisible(false);
推荐文章
- 警告:API ' variable . getjavacompile()'已过时,已被' variable . getjavacompileprovider()'取代
- 安装APK时出现错误
- 碎片中的onCreateOptionsMenu
- TextView粗体通过XML文件?
- 如何使线性布局的孩子之间的空间?
- DSL元素android.dataBinding。enabled'已过时,已被'android.buildFeatures.dataBinding'取代
- ConstraintLayout:以编程方式更改约束
- PANIC: AVD系统路径损坏。检查ANDROID_SDK_ROOT值
- 如何生成字符串类型的buildConfigField
- Recyclerview不调用onCreateViewHolder
- Android API 21工具栏填充
- Android L中不支持操作栏导航模式
- 如何在TextView中添加一个子弹符号?
- PreferenceManager getDefaultSharedPreferences在Android Q中已弃用
- 在Android Studio中创建aar文件