2013-08-30 21 views
3

我想用另一个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); 

    } 
} 

回答

3

试试这个:

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中伸出您可以通过<merge>更换根<LinearLayout>元素优化的XML。这是一个short documentation和一个SO 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 
} 
+0

是的,这应该工作。如果您的子容器布局特别复杂(大量子视图/选项),那么您始终可以使用扩展LinearLayout的类来设置您的child_container xml setContentView()并实例化该类,如此处所示。 –

+0

@gunar但是我的childContainer的实际内容呢。我需要它包含来自xml的内容。 – user2426316

+0

嗯......错过了那部分! :D让我想想 – gunar