requestFocus() returning false

一曲冷凌霜 提交于 2019-12-05 11:55:08

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();

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).

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