How to stop EditText from gaining focus at Activity startup in Android

后端 未结 30 2751
别那么骄傲
别那么骄傲 2020-11-21 06:40

I have an Activity in Android, with two elements:

  1. EditText
  2. ListView

When my Activity

30条回答
  •  悲哀的现实
    2020-11-21 07:12

    A simpler solution exists. Set these attributes in your parent layout:

    
    

    And now, when the activity starts this main layout will get focus by default.

    Also, we can remove focus from child views at runtime (e.g., after finishing child editing) by giving the focus to the main layout again, like this:

    findViewById(R.id.mainLayout).requestFocus();
    

    Good comment from Guillaume Perrot:

    android:descendantFocusability="beforeDescendants" seems to be the default (integer value is 0). It works just by adding android:focusableInTouchMode="true".

    Really, we can see that the beforeDescendants set as default in the ViewGroup.initViewGroup() method (Android 2.2.2). But not equal to 0. ViewGroup.FOCUS_BEFORE_DESCENDANTS = 0x20000;

    Thanks to Guillaume.

提交回复
热议问题