android - 如何使用另一个布局的新实例来扩充布局?

标签 android view android-linearlayout layout-inflater

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

相关文章:

android - Webview 在 android 5 中显示,但在 2.3 中不显示?

javascript - 切换 View 不会以 Angular 切换 Controller

android - 使用 ObjectAnimator 为 weightSum 属性设置动画

android - LinearLayout 在预 hive 上有分隔线

javascript - 如何使用 iscroll 和 Android WebView 将焦点字段带入 View

android - 动画:在 android 中,如何从一个中心点缩放和淡化由多行文本组成的 View

Android Gradle 避免 CMake 项目不必要的重建

android - Android 的高级动画

android - 可访问性如何影响 iOS 和 Android 中的字体大小?

android - 配置更改时为空对象引用