Is it possible to set a focus to a button widget which lies somewhere down in my layout? onCreate
of the activity my control/focus should be on that button programmatically.
Asked
Active
Viewed 1.3e+01k times
83

Jonik
- 80,077
- 70
- 264
- 372

Vinayak Bevinakatti
- 40,205
- 25
- 108
- 139
2 Answers
201
Yeah it's possible.
Button myBtn = (Button)findViewById(R.id.myButtonId);
myBtn.requestFocus();
or in XML
<Button ...><requestFocus /></Button>
Important Note: The button widget needs to be focusable
and focusableInTouchMode
. Most widgets are focusable
but not focusableInTouchMode
by default. So make sure to either set it in code
myBtn.setFocusableInTouchMode(true);
or in XML
android:focusableInTouchMode="true"

TWiStErRob
- 44,762
- 26
- 170
- 254

Pentium10
- 204,586
- 122
- 423
- 502
-
I trying it in onCreate method but its not working. I am creating buttons dynamically and adding the buttons in LinearLayout. Can any one please help me out? – Manoj Kumar Mar 16 '11 at 09:44
-
6it does not worked for me. I have an EditView in my page that always gets focus. – Bob Oct 23 '11 at 12:29
-
1`android:focusableInTouchMode="true"` required to click a button twice, the first click to set focus, the second click to make action. This is not appropriate for common flow. – Konstantin Konopko Apr 28 '21 at 13:36