Java 将布局元素访问到N的深度

Java 将布局元素访问到N的深度,java,php,android,Java,Php,Android,我这里有一个相当恼人的问题,因为我仍然试图把我所做的每一件事都内化 我目前有一个LinearLayout,然后在创建活动后,我会用按钮填充或膨胀其他几个LinearLayout,我的问题是,当我尝试访问按钮时,我似乎没有接近或深入LinearLayout,我能得到的只是LinearLayout(父)和其他LinearLayout(子),我相信有一种方法,我只是完全不知道怎么做 LinearLayout ->LinearLayout(Child1)->Button1, Button2

我这里有一个相当恼人的问题,因为我仍然试图把我所做的每一件事都内化

我目前有一个LinearLayout,然后在创建活动后,我会用按钮填充或膨胀其他几个LinearLayout,我的问题是,当我尝试访问按钮时,我似乎没有接近或深入LinearLayout,我能得到的只是LinearLayout(父)和其他LinearLayout(子),我相信有一种方法,我只是完全不知道怎么做

LinearLayout
 ->LinearLayout(Child1)->Button1, Button2, Button3
 ->LinearLayout(Child2)->Button4, Button5, Button6
我如何才能访问和获取按钮

我的来源

for (int x=0; x<ll.getChildCount(); x++){
  View v = ll.getChildAt(x);
  Class c = v.getClass();
  if(c == LinearLayout.class){
    for(int y=0; y< ; y++){
      **I know there is something that must be done here, likewise, is this the most
      efficient way of doing things?
    }
  }
 Log.i("test", c.getName());
}

对于(int x=0;x您应该能够简单地将
v
强制转换为
LinearLayout
,然后像访问其父级一样访问其子级。例如:

for (int x=0; x<ll.getChildCount(); x++){
  View v = ll.getChildAt(x);
  Class c = v.getClass();
  if(c == LinearLayout.class){
    //Cast to LinearLayout since View doesn't expose a way to access children
    LinearLayout innerLayout = (LinearLayout)v;
    for(int y=0; y<innerLayout.getChildCount() ; y++){
      Button b = (Button)innerLayout.getChildAt(y);

      //Do something with b
    }
  }
 Log.i("test", c.getName());
}
这是一个未经测试的示例(可能需要更好的异常处理,具体取决于您的需求和布局)但希望它能给你一个大致的想法。如果你想更不区分类型,你也可以使用cast来代替。如果需要,这将允许你潜在地使用不同类型的布局容器作为子类,因为它们是
ViewGroup
的子类(它们继承
getChildAt()
getChildCount()
from)

for (int i = 0; i < outerLayout.getChildCount(); ++i)
{
    try
    {
        LinearLayout innerLayout = (LinearLayout)outerLayout.getChildAt(i);

        if (innerLayout != null)
        {
            for (int j = 0; j < innerLayout.getChildCount(); ++j)
            {
                Button btn = (Button)innerLayout.getChildAt(j);

                //Do something with btn
            }
        }
    }
    catch (ClassCastException cEx)
    {
        Log.w("WARN", "Unexpected child type in outerLayout. " + cEx.getMessage());
    }
}