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

编辑文本列表视图

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

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

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


当前回答

我需要以编程方式明确关注所有领域。我刚刚在主布局定义中添加了以下两条语句。

myLayout.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
myLayout.setFocusableInTouchMode(true);

就这样。立刻解决了我的问题。谢谢,西尔弗,你给我指明了正确的方向。

其他回答

对我来说,在所有设备上工作的是:

    <!-- 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并重写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" />

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

 android:focusableInTouchMode="true"

如果要在活动开始时隐藏键盘。那就提一下

android:windowSoftInputMode="stateHidden"

到清单文件中的该活动。问题得到解决。

干杯

我做的最简单的事情是在onCreate中设置另一个视图的焦点:

myView.setFocusableInTouchMode(true);
myView.requestFocus();

这阻止了软键盘的出现,并且EditText中没有光标闪烁。