首页 文章

从LinearLayout获取子元素

提问于
浏览
47

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

有什么建议?

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

5 回答

  • 2

    你总是可以这样做:

    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
    }
    
  • 18

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

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

  • 3

    我会避免从视图的子项中静态地抓取元素 . 它现在可能会起作用,但会使代码难以维护,并且很容易在将来的版本中出现问题 . 如上所述,正确的方法是设置标签并通过标签获取视图 .

  • 79

    你可以这样做 .

    ViewGroup layoutCont= (ViewGroup) findViewById(R.id.linearLayout);
    getAllChildElements(layoutCont);
    public static final void getAllChildElements(ViewGroup layoutCont) {
        if (layoutCont == null) return;
    
        final int mCount = layoutCont.getChildCount();
    
        // Loop through all of the children.
        for (int i = 0; i < mCount; ++i) {
            final View mChild = layoutCont.getChildAt(i);
    
            if (mChild instanceof ViewGroup) {
                // Recursively attempt another ViewGroup.
                setAppFont((ViewGroup) mChild, mFont);
            } else {
                // Set the font if it is a TextView.
    
            }
        }
    }
    
  • 2
    LinearLayout layout = (LinearLayout)findViewById([whatever]);
    for(int i=0;i<layout.getChildCount();i++)
        {
            Button b =  (Button)layout.getChildAt(i)
        }
    

    如果它们都是按钮,否则转换为查看并检查课程

    View v =  (View)layout.getChildAt(i);
    if (v instanceof Button) {
         Button b = (Button) v;
    }
    

相关问题