How to set focus to a button widget programmatically?


Question

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.

1
78
6/16/2016 4:18:58 PM

Accepted Answer

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"
178
12/4/2014 5:07:11 PM

Try this:

btn.requestFocusFromTouch();

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon