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

编辑文本列表视图

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

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

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


当前回答

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

<LinearLayout 'dummy'>
<EditText et>

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

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

谢谢

其他回答

真正的问题是你根本不想让它有焦点吗?或者你不希望它显示虚拟键盘,因为它专注于EditText?我并不认为EditText在开始时有什么问题,但当用户没有明确要求关注EditText(并因此打开键盘)时,打开softInput窗口肯定是个问题。

如果是虚拟键盘的问题,请参阅AndroidManifest.xml<activity>元素文档。

android:windowSoftInputMode=“stateHidden”-输入活动时始终隐藏它。

或android:windowSoftInputMode=“stateUnchanged”-不要更改它(例如,如果它还没有显示,则不要显示它,但如果它在输入活动时处于打开状态,则保持它处于打开状态)。

我用提交按钮清除所有焦点

XML文件:

<LinearLayout
...
android:id="@+id/linear_layout"
android:focusableInTouchMode="true"> // 1. make this focusableInTouchMode...
</LinearLayout>

JAVA文件:

private LinearLayout mLinearLayout; // 2. parent layout element
private Button mButton;

mLinearLayout = findViewById(R.id.linear_layout);
mButton = findViewById(R.id.button);

mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLinearLayout.requestFocus(); // 3. request focus

            }
        });

我希望这对您有所帮助:)

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

我需要以编程方式明确关注所有领域。我刚刚在主布局定义中添加了以下两条语句。

myLayout.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
myLayout.setFocusableInTouchMode(true);

就这样。立刻解决了我的问题。谢谢,西尔弗,你给我指明了正确的方向。

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

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

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