简体   繁体   English

requestFocus()返回false

[英]requestFocus() returning false

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. 放大后的视图就像一个对话框,但是当我尝试使用requestFocus()聚焦对话框时,requestFocus()返回false表示我没有将注意力集中在视图上,但是当我手动点击放大后的视图时接收焦点。

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. 我先在按钮(用于扩大新视图)上清除焦点,然后再在扩大视图上调用requestFocus。

Regards 问候

A possible reason why the View.requestFocus() method returns false (does not successfully request focus) is because of the following reason: View.requestFocus()方法返回false(未成功请求焦点)的可能原因是由于以下原因:

"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." “如果视图不可聚焦(isFocusable()返回false),或者在设备处于触摸模式时可聚焦并且在触摸模式下不可聚焦(isFocusableInTouchMode()),则视图实际上不会获得焦点。”

Check if both isFocusable() and isFocusableInTouchMode() return true. 检查isFocusable()isFocusableInTouchMode()是否都返回true。 If not, you could possibly force them by using the setFocusable() and setFocusableInTouchMethod() as seen below. 如果没有,则可以使用setFocusable()setFocusableInTouchMethod()强制使用它们,如下所示。

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: 在通货膨胀时调用requestFocus()还为时过早,尝试调用如下内容:

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(); 此外,也不必调用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). 按钮本身(实际上,我不推荐这样做,因为该框架将尝试将焦点移交给其他人,并且您已经知道应该集中哪个视图)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM