我在Android中有一个活动,包含两个元素:
编辑文本列表视图
当“活动”启动时,EditText立即具有输入焦点(闪烁光标)。我不希望任何控件在启动时具有输入焦点。我尝试了:
EditText.setSelected(false);
EditText.setFocusable(false);
没有运气。如何说服EditText在“活动”启动时不选择自己?
我在Android中有一个活动,包含两个元素:
编辑文本列表视图
当“活动”启动时,EditText立即具有输入焦点(闪烁光标)。我不希望任何控件在启动时具有输入焦点。我尝试了:
EditText.setSelected(false);
EditText.setFocusable(false);
没有运气。如何说服EditText在“活动”启动时不选择自己?
当前回答
在onCreate方法中添加以下内容:
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
其他回答
存在更简单的解决方案。在父布局中设置这些属性:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainLayout"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true" >
现在,当活动开始时,默认情况下,主布局将聚焦。
此外,我们可以在运行时(例如,在完成子编辑后)通过再次将焦点放在主布局上,从子视图中移除焦点,如下所示:
findViewById(R.id.mainLayout).requestFocus();
Guillaume Perrot的好评:
android:descendantFocusability=“beforeDescendants”似乎是默认值(整数值为0)。只需添加android:focuableInTouchMode=“true”。
实际上,我们可以看到,在ViewGroup.initViewGroup()方法中,beforeDescendants被设置为默认值(Android 2.2.2)。但不等于0。ViewGroup.FOCUS_BEFORE_DESCENTANS=0x20000;
感谢纪尧姆。
我遇到了这样的问题,这是由于我的选择。第一个状态是焦点,即使我的视图被禁用了,它也采用了焦点状态,因为它是第一个匹配并使用它的状态。您可以像这样将第一个状态设置为禁用:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/text_field_disabled" android:state_enabled="false"/>
<item android:drawable="@drawable/text_field_focused" android:state_focused="true"/>
<item android:drawable="@drawable/text_field_normal"/>
在父布局(例如LinearLayout或ConstraintLayout)中添加标签android:focusableInTouchMode=“true”和android:focusable=“true”将解决该问题。
<!-- Dummy item to prevent AutoCompleteTextView from receiving focus -->
<LinearLayout
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="0px"
android:layout_height="0px"/>
<!-- :nextFocusUp and :nextFocusLeft have been set to the id of this component
to prevent the dummy from receiving focus again -->
<AutoCompleteTextView android:id="@+id/autotext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:nextFocusUp="@id/autotext"
android:nextFocusLeft="@id/autotext"/>
做这个,完成你的工作!
android:focusable="true"
android:focusableInTouchMode="true"
当您的活动打开时,键盘会自动可见,这会导致EditText聚焦。您可以通过在manifest.xml文件的活动标记中写入以下行来禁用键盘。
android:windowSoftInputMode="stateAlwaysHidden|adjustPan"