为什么 Android 中有 2 个 setFocusable 方法?

Why are there 2 setFocusable methods in Android?

我试图设置组件的可聚焦性并找到了这两种方法,希望我可以使用它们使组件仅在用户触摸时可聚焦,而不是在以编程方式请求时:

myComponent.setFocusable(false);
myComponent.setFocusableInTouchMode(true);

然后我看了their documentation

public void setFocusable (boolean focusable)

Set whether this view can receive the focus. Setting this to false will also ensure that this view is not focusable in touch mode.


public void setFocusableInTouchMode (boolean focusableInTouchMode)

Set whether this view can receive focus while in touch mode. Setting this to true will also ensure that this view is focusable.

所以,如果调用其中一个隐式调用另一个,为什么要区分?

请注意,调用 setFocusable(true) 不会调用 setFocusableInTouchMode(true),调用 setFocusableInTouchMode(false) 也不会调用 setFocusable(false)。这不是平等。

并不是总是互相打电话。想象一下,有一个可以通过键盘聚焦但不能通过触摸事件聚焦的视图:

setFocusable(true);
setFocusableInTouchMode(false);

视图系统中有两个标志:FOCUSABLEFOCUSABLE_IN_TOUCH_MODE。每个方法 sets/clears 各自的标志,并且有 两种 一种方法影响另一种方法状态的情况:

  1. 调用 setFocusableInTouchMode(true) 将确保设置 FOCUSABLE 标志。
  2. 调用 setFocusable(false) 将确保清除 FOCUSABLE_IN_TOUCH_MODE 标志。

换句话说,FOCUSABLE_IN_TOUCH_MODE依赖于全局FOCUSABLE标志,没有它就不能设置。

模式的区别有点遗留。这个想法是为了区分用户何时使用方向键或轨迹球导航 UI 与点击触摸屏。如今,设备几乎总是处于 "touch mode",但仍有少数情况会检查底层 FOCUSABLE 标志。主要是在通过输入法的 return 键寻找 "next" 视图时或当辅助功能打开时。

有关不同模式的更多详细信息,您可以阅读 SDK View Documentation 的 "Focus Handling" 和 "Touch Mode" 部分。