我在Android中有一个活动,包含两个元素:

编辑文本列表视图

当“活动”启动时,EditText立即具有输入焦点(闪烁光标)。我不希望任何控件在启动时具有输入焦点。我尝试了:

EditText.setSelected(false);
EditText.setFocusable(false);

没有运气。如何说服EditText在“活动”启动时不选择自己?


当前回答

<TextView
    android:id="@+id/textView01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:singleLine="true"
    android:ellipsize="marquee"
    android:marqueeRepeatLimit="marquee_forever"
    android:focusable="true"
    android:focusableInTouchMode="true"
    style="@android:style/Widget.EditText"/>

其他回答

隐藏键盘的最简单方法是使用setSoftInputMode

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

或者可以使用InputMethodManager并像这样隐藏键盘。

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

已经提供了很多有效的答案,但我认为我们可以使用以下简单方法做得更好

//set focus to input field
private fun focusHere() {
    findViewById<TextView>(R.id.input).requestFocus()
}

使用任何其他视图id来设置该视图的焦点,以代替R.id.input中的输入。

在父布局(例如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"/>

存在更简单的解决方案。在父布局中设置这些属性:

<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;

感谢纪尧姆。

是的,我做了同样的事情——创建一个“虚拟”线性布局,以获得初始焦点。此外,我设置了“下一个”焦点ID,这样用户在滚动一次后就不能再聚焦了:

<LinearLayout 'dummy'>
<EditText et>

dummy.setNextFocusDownId(et.getId());
 
dummy.setNextFocusUpId(et.getId());
 
et.setNextFocusUpId(et.getId());

很多工作只是为了摆脱对视图的关注。

谢谢