android – 如何使用另一个布局的新实例来扩充布局?
作者:互联网
我想用另一个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,view,android-linearlayout,layout-inflater 来源: https://codeday.me/bug/20190624/1282588.html