我在Android中有一个活动,包含两个元素:
编辑文本列表视图
当“活动”启动时,EditText立即具有输入焦点(闪烁光标)。我不希望任何控件在启动时具有输入焦点。我尝试了:
EditText.setSelected(false);
EditText.setFocusable(false);
没有运气。如何说服EditText在“活动”启动时不选择自己?
我在Android中有一个活动,包含两个元素:
编辑文本列表视图
当“活动”启动时,EditText立即具有输入焦点(闪烁光标)。我不希望任何控件在启动时具有输入焦点。我尝试了:
EditText.setSelected(false);
EditText.setFocusable(false);
没有运气。如何说服EditText在“活动”启动时不选择自己?
当前回答
对我来说,在所有设备上工作的是:
<!-- fake first focusable view, to allow stealing the focus to itself when clearing the focus from others -->
<View
android:layout_width="0px"
android:layout_height="0px"
android:focusable="true"
android:focusableInTouchMode="true" />
只需将此作为一个视图放在有问题的聚焦视图之前,就可以了。
其他回答
以下内容将阻止EditText在创建时获取焦点,但当您触摸它们时会抓住它。
<EditText
android:id="@+id/et_bonus_custom"
android:focusable="false" />
因此,在xml中将focusable设置为false,但关键是在java中,您可以添加以下侦听器:
etBonus.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
v.setFocusable(true);
v.setFocusableInTouchMode(true);
return false;
}
});
因为您返回的是false,即不使用事件,所以聚焦行为将照常进行。
这是最完美、最简单的解决方案。我总是在我的应用程序中使用这个。getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
如果要在活动开始时隐藏键盘。那就提一下
android:windowSoftInputMode="stateHidden"
到清单文件中的该活动。问题得到解决。
干杯
在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()中尝试:)
在父布局(例如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"/>