我想用另一个 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);
}
}
最佳答案
试试这个:
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,您可以通过替换根 <LinearLayout>
来优化 xml带有 <merge>
的元素.这是一个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
}
关于android - 如何使用另一个布局的新实例来扩充布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18536388/