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

编辑文本列表视图

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

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

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


当前回答

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

<LinearLayout 'dummy'>
<EditText et>

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

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

谢谢

其他回答

只需在EditText的父布局中添加android:focuableInTouchMode=“true”,您就可以摆脱这种尴尬的行为。

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

以下内容将阻止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,即不使用事件,所以聚焦行为将照常进行。

从EditText in xml文件中删除<requestFocus/>。

<EditText
       android:id="@+id/emailField"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:inputType="textEmailAddress">
    
       //`<requestFocus />` /* <-- remove this tags */
    </EditText>

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

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

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

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