问题
I am inflating a view when a button is pressed. The inflated view is like a dialog box, however when I try to get focus on the dialog box with requestFocus()
, requestFocus() returns false means I am not getting focus on the view, but when I manually tap the inflated view, it recieves focus.
What am I doing wrong?
I clear focus from the button (which is used to inflated the new view) before I call requestFocus on inflated view.
Regards
回答1:
A possible reason why the View.requestFocus() method returns false (does not successfully request focus) is because of the following reason:
"A view will not actually take focus if it is not focusable (isFocusable() returns false), or if it is focusable and it is not focusable in touch mode (isFocusableInTouchMode()) while the device is in touch mode."
Check if both isFocusable()
and isFocusableInTouchMode()
return true. If not, you could possibly force them by using the setFocusable()
and setFocusableInTouchMethod()
as seen below.
View view;
view.setFocusable(true);
view.setFocusableInTouchMode(true);
view.requestFocus();
回答2:
It's too early to call requestFocus() at inflation time, try to call something like:
button.post(new Runnable(){
@Override
public void run(){
inflatedView.requestFocus();
}
});
which will schedule this call to the main queue (so it will be called in the future), after the main thread finish its job here.
Also, it's not necessary to call clearFocus();
on the button itself (and actually, I don't recommend it, since the framework will try to give focus to someone else, and you already know what view should be focused).
来源:https://stackoverflow.com/questions/20890306/requestfocus-returning-false