I have an Activity
in Android, with two elements:
EditText
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?
The following will stop edittext from taking focus when created, but grab it when you touch them.
So you set focusable to false in the xml, but the key is in the java, which you add the following listener:
Because you are returning false, i.e. not consuming the event, the focusing behavior will proceed like normal.
Excellent answers from Luc and Mark however a good code sample is missing. Adding the tag
android:focusableInTouchMode="true"
to<LinearLayout>
like the following example will fix the problem.Being that I don't like to pollute the XML with something that is related to functionality, I created this method that "transparently" steals the focus from the first focusable view and then makes sure to remove itself when necessary!
For me, what worked on all devices is this:
Just put this as a view before the problematic focused view, and that's it.
I needed to clear focus from all fields programmatically. I just added the following two statements to my main layout definition.
That's it. Fixed my problem instantly. Thanks, Silver, for pointing me in the right direction.
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:
Good comment from Guillaume Perrot:
Really, we can see that the
beforeDescendants
set as default in theViewGroup.initViewGroup()
method (Android 2.2.2). But not equal to 0.ViewGroup.FOCUS_BEFORE_DESCENDANTS = 0x20000;
Thanks to Guillaume.