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

编辑文本列表视图

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

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

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


当前回答

在第一个可编辑字段之前尝试以下操作:

<TextView  
        android:id="@+id/dummyfocus" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:text="@string/foo"
        />

findViewById(R.id.dummyfocus).setFocusableInTouchMode(true);
findViewById(R.id.dummyfocus).requestFocus();

其他回答

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

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

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

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

在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()中尝试:)

以下内容在Manifest中对我有效。写

<activity
android:name=".MyActivity"
android:windowSoftInputMode="stateAlwaysHidden"/>

当您的活动打开时,键盘会自动可见,这会导致EditText聚焦。您可以通过在manifest.xml文件的活动标记中写入以下行来禁用键盘。

android:windowSoftInputMode="stateAlwaysHidden|adjustPan"

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