requestFocus() returning false

本小妞迷上赌 提交于 2019-12-22 08:22:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!