A simpler solution exists. Set these attributes in your parent layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainLayout"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true" >
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.