How to set focus to a button widget programmatically?

AndroidAndroid WidgetAndroid Button

Android Problem Overview


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.

Android Solutions


Solution 1 - Android

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 - Android

Try this:

btn.requestFocusFromTouch();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVinayak BevinakattiView Question on Stackoverflow
Solution 1 - AndroidPentium10View Answer on Stackoverflow
Solution 2 - AndroidZanView Answer on Stackoverflow