android 辅助功能 focusSearch 没有 return 任何节点

android Accessibility focusSearch does not return any node

我的辅助功能服务将通过可聚焦节点。我正在尝试为此使用 focusSearch 函数,但这并没有返回任何节点。但是布局包含可聚焦的项目。这是布局:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:focusable="true"
        android:text="Button" />

    <TextView
        android:id="@+id/text"
        android:layout_width="122dp"
        android:layout_height="fill_parent"
        android:text="Hello World2" />

        <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:focusable="true"
        android:text="Button2" />


</LinearLayout>

所以我尝试找到第一个按钮:

AccessibilityNodeInfo root = getRootInActiveWindow();
AccessibilityNodeInfo node1 = null;
node1 = root.findAccessibilityNodeInfosByViewId("my.app:id/button1").get(0);
//returns button view
node1 = root.focusSearch(View.FOCUS_DOWN); //returns null
node1 = root.focusSearch(View.FOCUS_LEFT); //returns null
node1 = root.focusSearch(View.FOCUS_RIGHT); //returns null
node1 = root.focusSearch(View.FOCUS_FORWARD); //returns null

但是使用 findFocus 它会返回框架布局

node1 = root.findFocus(AccessibilityNodeInfo.FOCUS_ACCESSIBILITY);
//returns node of the main framelayout

然后我用这个节点进行下一次搜索,但还是没有找到。

node1 = node1.focusSearch(View.FOCUS_FORWARD); //returns null

当我调用 findfocus 而不是 focusSearch 时,我得到了相同的节点

node1 = node1.findFocus(AccessibilityNodeInfo.FOCUS_ACCESSIBILITY);
//returns the same node

所以问题是我如何遍历布局中的可聚焦节点?

这是一个常见的误解。您正在搜索的是可以获取输入焦点的对象(想想 EditText 控件)。这与 Accessibility Focus 有着根本的不同。您的布局中没有可聚焦的输入控件。

您想要的功能是:

someAccessibilityNodeInfo.getTraversalAfter();

someAccessibilityNodeInfo.getTraversalBefore();

没有 up/down 等价物。尽管您可以根据需要进行计算。您可以将可访问性可聚焦节点的整个层次结构存储在一个数组中,并根据 x 和 y 位置计算 up/down。

没错!返回视图容器,因为它们存在于树中。

你需要的是叶节点。

此代码将为您提供可聚焦的节点(叶节点)列表:

ArrayList<AccessibilityNodeInfo> inputViewsList = new ArrayList<AccessibilityNodeInfo>();
AccessibilityNodeInfo rootNode = getRootInActiveWindow();
refreshChildViewsList(rootNode);
for(AccessibilityNodeInfo mNode : inputViewsList){
    if(mNode.isFocusable()){
        //do whatever you want with the node...
    }
}

refreshChildViewsList方法:

private void refreshChildViews(AccessibilityNodeInfo rootNode){
    int childCount = rootNode.getChildCount();
    for(int i=0; i<childCount ; i++){
        AccessibilityNodeInfo tmpNode = rootNode.getChildAt(i);
        int subChildCount = tmpNode.getChildCount();
        if(subChildCount==0){
            inputViewsList.add(tmpNode);
            return; 
        } else {
            refreshChildViews(tmpNode);
        } 
    } 
} 

如果此代码有任何问题,请告诉我!