【问题标题】:Android getting the view treeAndroid获取视图树
【发布时间】:2020-04-30 18:25:29
【问题描述】:

我想获取活动中的所有视图。喜欢;

ArrayList<View> views = new Arraylist<>();

views.addAll(getAllViewsFromActivity());

我想要的是“getAllViewsFromActivity()”函数。我显然希望获得所有视图,即使是一个按钮。但我找不到任何明确的答案。

对于进度,一定是这样的:

                         MainView : getWindow().getDecorView()
                   -                                                  -
          RelativeLayout
        -                - 
   Button              LinearLayout
                               -
                               TextView

如何以编程方式在 Android 中获取此树?并且还假设我得到了这棵树,我还可以识别它们的类型,例如:view instanceof Button 吗?

【问题讨论】:

  • 可以通过getChild获取,但会是深度循环。为什么要得到它,也许我们应该改变目标的方式
  • @Lenoarod 我的项目编码不好,我不想完成所有设计。设计有 3 种颜色,黑色白色和灰色,我只想让颜色相反。只是想设置相反的颜色。
  • 根据你的描述我给个答案,你可以试试。

标签: android user-interface view


【解决方案1】:

您想要获得的视图很清晰。所以你可以使用父视图(如LinearLayout)来获取孩子。所以你可以试试这个:

int count = parent.getChildCount();
for(int i =0; i< count;i++){
   View child = parent.getChildAt(i);
   //here you can to chage the view some proper. 
   //if you only want to change the background color, it belongs to view, don't 
   // need to cast.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 2013-07-18
    • 2011-05-06
    相关资源
    最近更新 更多