How to set focus to a button widget programmatically?
124,540
Solution 1
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"
Solution 2
Try this:
btn.requestFocusFromTouch();
Related videos on Youtube
Author by
Vinayak Bevinakatti
Hi! I am an experienced mobile app enthusiast. I enjoy creating apps for Android and iOS. I've worked on Android, iOS, BlackBerry platforms for developing both native and hybrid apps. "Be Proactive, Not Reactive"
Updated on May 19, 2020Comments
-
Vinayak Bevinakatti about 4 years
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. -
Manoj Kumar about 13 yearsI 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?
-
Bobs over 12 yearsit does not worked for me. I have an EditView in my page that always gets focus.
-
Konstantin Konopko about 3 years
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.