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

编辑文本列表视图

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

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

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


当前回答

最简单的方法是在Manifest.xml文件的活动标记中添加android:windowSoftInputMode=“stateAlwaysHidden”

其他回答

请尝试clearFocus()而不是setSelected(false)。Android中的每个视图都具有可聚焦性和可选择性,我认为您只需要清除焦点。

最简单的方法是在Manifest.xml文件的活动标记中添加android:windowSoftInputMode=“stateAlwaysHidden”

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

在onCreate()中禁用它

final KeyListener edtTxtMessageKeyListener = edtTxtMessage.getKeyListener();
edtTxtMessage.setCursorVisible(false);
edtTxtMessage.setKeyListener(null);

最后在EditText的onClick()中启用它

edtTxtMessage.setCursorVisible(true);
edtTxtMessage.setKeyListener(edtTxtMessageKeyListener);

但问题是,我们必须在第一次使用OnScreenKeyboard时单击两下。

@变通办法

InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);

也可以在onClick()中尝试:)

在Activity的onCreate中,只需在EditText元素上添加useclearFocus()。例如

edittext = (EditText) findViewById(R.id.edittext);
edittext.clearFocus();

如果您想将焦点转移到另一个元素,请使用requestFocus()。例如

button = (Button) findViewById(R.id.button);
button.requestFocus();