【问题标题】:how to get all child view direct and hirechery in android如何在android中直接获取所有子视图和hirechery
【发布时间】:2015-03-23 07:56:16
【问题描述】:

我有这样的用户界面:

<RelativeLayout>
       <TextView />
       <RelativeLayout>
             <TextView />
             <TextView />
             <LinearLayout>
                  <TextView />
             </LinearLayout>
       </RelativeLayout>
</RelativeLayout>

我想以编程方式访问所有 TextView 并更改一些属性,但是 我不想使用 id 和 findViewById,因为我有一个多布局,我想在其中执行相同的更改,即:更改 TextViews 的字体。

如何访问所有 TextView,无论是直接视图还是层次视图,例如循环或列表中的 RelativeLayout?

【问题讨论】:

  • 编写一个递归(甚至是线性)算法来遍历视图层次结构是微不足道的。大多数解决方案已经在here 中进行了概述。您需要做的就是为您感兴趣的特定视图类型添加一些类型检查。

标签: android android-ui


【解决方案1】:
    LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.my_linear_layout);

    for(i = 0; i <= mLinearLayout.getChildCount(); i++){ 
        View view = mLinearLayout.getChildAt(i); 
        if (view instanceof TextView){ 
            TextView textView = (TextView) view;
            // TODO do your stuff 
        } 
    }

如果您的 RelativeLayout 中有 ViewGroups,那么您需要编写一个递归方法。

【讨论】:

  • "如果您的 RelativeLayout (...) 中有 ViewGroups" - 根据问题,这里没有太多 if。 .. 第一级有一个RelativeLayout,第二级有一个LinearLayout
  • 他应该研究一些来提高自己:P
猜你喜欢
  • 2010-10-22
  • 2011-07-23
  • 2014-12-16
  • 1970-01-01
  • 1970-01-01
  • 2012-01-13
  • 2011-10-18
  • 2015-08-15
  • 1970-01-01
相关资源
最近更新 更多