【问题标题】:How can I inflate a layout with new instances of the another layout?如何使用另一个布局的新实例来扩展布局?
【发布时间】:2013-09-03 09:19:47
【问题描述】:

我想用另一个 LinearLayout 的多个实例来扩充 LinearLayout。我怎样才能做到这一点?我的问题是我似乎总是使用相同的实例,因此一遍又一遍地添加该实例。

简而言之:我需要一种将LinearLayout 子级的新实例添加到另一个LinearLayout 父级的方法。

这是我到目前为止所做的:

private void setupContainers() {
    LayoutInflater layoutInflater = (LayoutInflater)this.getSystemService(MainActivity.LAYOUT_INFLATER_SERVICE);
    LinearLayout parentContainer = (LinearLayout)this.findViewById(R.id.parent_container);

    for (int i = 0; i < someNumber; i++) {

        LinearLayout childContainer = (LinearLayout) layoutInflater.inflate(R.layout.child_container, null);
        parentContainer.addView(childContainer);

    }
}

【问题讨论】:

    标签: android view android-linearlayout layout-inflater


    【解决方案1】:

    试试这个:

    for (int i = 0; i < someNumber; i++) {
        LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); // or any other layout params that suit your needs
        LinearLayout childContainer = new LinearLayout(this);
        parentLayout.addView(childContainer, params)
    }
    

    编辑

    考虑到您需要使用 XML 中的内容,您需要创建一个自定义类来扩展 LinearLayout 并在其中初始化它的所有属性。比如:

    public class MyLinearLayout extends LinearLayout {
    
        public MyLinearLayout(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init(context);
        }
    
        public MyLinearLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
            init(context);
        }
    
        public MyLinearLayout(Context context) {
            super(context);
            init(context);
        }
    
        private void init(Context context) {
            inflate(context, R.id.R.layout.child_container, this);
            // setup all your Views from here with calls to getViewById(...);
        }
    
    }
    

    此外,由于您的自定义 LieanrLayout 从 LinearLayout 扩展,您可以通过将根 &lt;LinearLayout&gt; 元素替换为 &lt;merge&gt; 来优化 xml。这是short documentationSO link。于是for循环就变成了:

    for (int i = 0; i < someNumber; i++) {
        LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); // or any other layout params that suit your needs
        LinearLayout childContainer = new MyLinearLayout(this);
        parentLayout.addView(childContainer, params); // feel free to add or not the LayoutParams object
    }
    

    【讨论】:

    • 是的,这应该可以。如果您的子容器布局特别复杂(很多子视图/选项),那么您始终可以创建一个扩展 LinearLayout 的类,该类使用 setContentView() 设置您的 child_container xml 并实例化该类,如此处所示。
    • @gunar 但是我的 childContainer 的实际内容呢?我需要它来包含来自 xml 的内容。
    • 嗯...错过了那部分! :D 让我想想
    • 正如 Andrew 所说:您需要创建一个从 LinearLayout 扩展并从 xml 扩展的自定义类。我会尽快更新答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多