首页 > 解决方案 > 动态地将框架布局添加到水平滚动视图中

问题描述

我正在尝试将一些自定义框架布局动态添加到水平滚动视图中。我正在考虑在 xml 中创建具有嵌套线性布局的水平滚动视图,并使用 java 添加一些框架布局。像这样的东西:

LinearLayout parent = (LinearLayout) findViewById(R.id.parent);
for(int i=0; i<5; i++) {
    FrameLayout child = new FrameLayout(this);
    child.setBackgroundResource(R.drawable.card);
    //add this linear layout to the parent
}

我见过一些使用 Layout Inflater 的解决方案,但据我了解,它使用了我资源中的布局。相反,如果可能,我想创建没有 xml 的框架布局。

谢谢

编辑:

这是我的xml

<HorizontalScrollView
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:background="@android:color/holo_blue_light">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/parent"
        android:orientation="horizontal">

    </LinearLayout>

</HorizontalScrollView>

标签: androidandroid-layout

解决方案


假设您有以下代码:

FrameLayout child = new FrameLayout(this);
child.setBackgroundResource(R.drawable.card);
parent.addView(child);

因为您没有LayoutParams为此视图指定任何内容,所以 LinearLayout 将为您生成默认的 LayoutParams。它是这样做的:

@Override
protected LayoutParams generateDefaultLayoutParams() {
    if (mOrientation == HORIZONTAL) {
        return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    } else if (mOrientation == VERTICAL) {
        return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    }
    return null;
}

您的 LinearLayout 是水平的,因此它将WRAP_CONTENT用于两个维度。但是你的 FrameLayout 没有任何内容,所以这和 0 一样。

您可以通过如下更改代码来手动指定 LayoutParams(使用像素尺寸):

FrameLayout child = new FrameLayout(this);
child.setBackgroundResource(R.drawable.card);

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(200, 200); // px units
child.setLayoutParams(params);

parent.addView(child);

或者,您可以将内容添加到 FrameLayout 以对其进行包装:

FrameLayout child = new FrameLayout(this);
child.setBackgroundResource(R.drawable.card);

TextView tv = new TextView(this);
tv.setText("hello world");
child.addView(tv);

parent.addView(child);

推荐阅读