Android - getCurrentFocus().clearFocus() 时会发生什么

Android - What happen when getCurrentFocus().clearFocus()

我在使用 EditText 或其他 input/picker 时遇到了一些问题,这不是我当前 view/fragment 突然出现的人。我的新片段在创建时从传递的片段调用 EditText 或选择器。

我知道解决这个问题的方法。我可以使用一些带有 requestFocus() 的虚拟视图。 或者有时(这就是问题所在)activity.getCurrentFocus().clearFocus(); 但是最后一个看起来失败了1/2。

所以这是我的问题:如何工作 getCurrentFocus(),他是否只检查当前 activity 视图或子视图作为片段?为什么每次都不起作用?

如果有人对此有所了解,将不胜感激:D

如果每次获得焦点的视图都不一样,你可以试试这样:

View current = getCurrentFocus();
if (current != null) {
current.clearFocus();
}

如果使用 clearFocus() 无法正常工作,您可以:

<LinearLayout 
android:id="@+id/my_layout" 
android:focusable="true" 
android:focusableInTouchMode="true" ...>

到最顶层的布局视图(线性布局)。要从所有 Buttons/EditTexts 等中移除焦点,您可以执行

LinearLayout myLayout = (LinearLayout) activity.findViewById(R.id.my_layout);
myLayout.requestFocus();

来自文档

When a View clears focus the framework is trying to give focus to the first focusable View from the top. Hence, if this View is the first from the top that can take focus, then all callbacks related to clearing focus will be invoked after which the framework will give focus to this view.


希望这对您有所帮助。