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

编辑文本列表视图

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

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

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


当前回答

它可以通过继承EditText并重写onTouchEvent来实现。

class NonFocusableEditText: EditText {

    constructor(context: Context): super(context)
    constructor(context: Context, attrs: AttributeSet?): super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int): super(context, attrs, defStyleAttr)

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        return if (isFocusable) super.onTouchEvent(event) else false
    }
}

然后,您可以像普通的EditText一样在版面中使用它:

<com.yourpackage.NonFocusableEditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"    
        android:hint="@string/your_hint"
        android:imeOptions="actionDone"
        android:inputType="textNoSuggestions" />

其他回答

隐藏键盘的最简单方法是使用setSoftInputMode

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

或者可以使用InputMethodManager并像这样隐藏键盘。

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

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

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

<LinearLayout 'dummy'>
<EditText et>

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

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

谢谢

在父版面中写入此行。。。

 android:focusableInTouchMode="true"

做这个,完成你的工作!

android:focusable="true"
android:focusableInTouchMode="true"