Stop EditText from gaining focus at Activity start

2018-12-31 01:33发布

I have an Activity in Android, with two elements:

  1. EditText
  2. ListView

When my Activity starts, the EditText immediately has input focus (flashing cursor). I don't want any control to have input focus at startup. I tried:

EditText.setSelected(false);

No luck. How can I convince the EditText to not select itself when the Activity starts?

30条回答
只若初见
2楼-- · 2018-12-31 02:20

The problem seems to come from a property that I can only see in the XML form of the layout.

Make sure to remove this line at the end of the declaration within the EditText XML tags:

<requestFocus />

That should give something like that :

<EditText
   android:id="@+id/emailField"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:inputType="textEmailAddress">

   //<requestFocus /> /* <-- without this line */
</EditText>
查看更多
查无此人
3楼-- · 2018-12-31 02:20

Simplest answer, just add this in parent layout of the XML.

android:focusable="true" 
android:focusableInTouchMode="true"
查看更多
孤独总比滥情好
4楼-- · 2018-12-31 02:20

If you have another view on your activity like a ListView, you can also do:

ListView.requestFocus(); 

in your onResume() to grab focus from the editText.

I know this question has been answered but just providing an alternative solution that worked for me :)

查看更多
梦寄多情
5楼-- · 2018-12-31 02:22

Add following in onCreate method:

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
查看更多
旧时光的记忆
6楼-- · 2018-12-31 02:22

Write this line in your Parent Layout...

 android:focusableInTouchMode="true"
查看更多
忆尘夕之涩
7楼-- · 2018-12-31 02:22

The simplest thing I did is to set focus on another view in onCreate:

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

This stopped the soft keyboard coming up and there was no cursor flashing in the EditText.

查看更多
登录 后发表回答