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

编辑文本列表视图

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

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

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


当前回答

您可以通过使用请求焦点并使用键盘隐藏代码来指定其他小部件的焦点。

其他回答

从EditText in xml文件中删除<requestFocus/>。

<EditText
       android:id="@+id/emailField"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:inputType="textEmailAddress">
    
       //`<requestFocus />` /* <-- remove this tags */
    </EditText>

利用其他海报提供的信息,我使用了以下解决方案:

在布局XML中

<!-- Dummy item to prevent AutoCompleteTextView from receiving focus -->
<LinearLayout
    android:id="@+id/linearLayout_focus"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:layout_width="0px"
    android:layout_height="0px"/>

<!-- AUTOCOMPLETE -->
<AutoCompleteTextView
    android:id="@+id/autocomplete"
    android:layout_width="200dip"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dip"
    android:inputType="textNoSuggestions|textVisiblePassword"/>

在onCreate()中

private AutoCompleteTextView mAutoCompleteTextView;
private LinearLayout mLinearLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mylayout);

    //get references to UI components
    mAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
    mLinearLayout = (LinearLayout) findViewById(R.id.linearLayout_focus);
}

最后,在onResume()中

@Override
protected void onResume() {
    super.onResume();

    //do not give the editbox focus automatically when activity starts
    mAutoCompleteTextView.clearFocus();
    mLinearLayout.requestFocus();
}

在Manifest.xml文件的活动标记中添加android:windowSoftInputMode=“stateAlwaysHidden”。

来源

您可以在布局的第一个TextView中将“focusable”和“focustable in touch mode”设置为true。这样,当活动开始时,TextView将被聚焦,但由于其性质,您将不会在屏幕上看到任何聚焦,当然,也不会显示键盘。。。

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

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

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