从LinearLayout获取子元素

Cod*_*ody 54 java android android-linearlayout

有没有办法获取LinearLayout的子元素?我的代码返回一个视图(linearlayout),但我需要访问布局中的特定元素.

有什么建议?

(是的,我知道我可以使用findViewById,但我在java中创建布局/子项 - 而不是XML.)

Ale*_*s G 83

你总是可以这样做:

LinearLayout layout = setupLayout();
int count = layout.getChildCount();
View v = null;
for(int i=0; i<count; i++) {
    v = layout.getChildAt(i);
    //do something with your child element
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢.有用的是:`TextView tv =(TextView)((LinearLayout)v).getChildAt(0);` (11认同)

Asa*_*ahi 19

我认为这可能会有所帮助:findViewWithTag()

将TAG设置为您添加到布局的每个View,然后像使用ID一样通过TAG获取该View


Ann*_*rom 7

LinearLayout layout = (LinearLayout)findViewById([whatever]);
for(int i=0;i<layout.getChildCount();i++)
    {
        Button b =  (Button)layout.getChildAt(i)
    }
Run Code Online (Sandbox Code Playgroud)

如果它们都是按钮,否则强制转换以查看和检查类

View v =  (View)layout.getChildAt(i);
if (v instanceof Button) {
     Button b = (Button) v;
}
Run Code Online (Sandbox Code Playgroud)


小智 5

我会避免从视图的子级中静态获取元素。它可能现在可以工作,但是会使代码难以维护,并且容易在将来的发行版中被破坏。如上所述,正确的做法是设置标签并通过标签获取视图。