【问题标题】:Add View as first child将视图添加为第一个孩子
【发布时间】:2012-11-03 10:12:38
【问题描述】:

我正在开发一个带有 ScrollView 的应用程序,其中的大部分视图都在 onCreate 时添加到 RelativeLayout。像这样:

我还想在运行时添加视图。这些被添加到上图中的当前位置。我想要做的是在运行时在想要的位置添加视图。

我怎样才能做到这一点?

【问题讨论】:

    标签: android android-layout scrollview android-relativelayout


    【解决方案1】:

    按照建议将ScrollView 内的布局转换为LinearLayout,然后使用:

    addView(child, index, layoutParams)

    在您的LinearLayout 上。

    【讨论】:

      【解决方案2】:

      将此设置为滚动视图 android:orientation="vertical" 和 android:scrollbars="vertical"

      【讨论】:

      • 屏幕实际上处于横向模式,滚动视图从屏幕顶部到底部。以及java中定义的滚动和真实布局。你知道如何解决这个问题吗?
      【解决方案3】:

      您可以将RelativeLayout 转换为LinearLayout 并设置android:orientation="vertical"。

      在此 LinearLayout 中,您可以使用 android:orientation="horizontal" 为您的水平视图嵌套另一个 LinearLayout。

      这样,对于每个水平视图部分,您可以将子 LinearLayout 添加到您的父 Linearlayout,并且这些子元素中的每一个都将根据您的需要垂直排列在另一个下方。

      【讨论】:

        【解决方案4】:

        我认为答案包含在最后一行 (parent.addView(brick, 0);),但为了排除误解,我已经发布了所有代码。 现在我也在做同样的事情

        xml
        activity_view.xml

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_height="match_parent"
            android:layout_width="match_parent"
        >
            <ScrollView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
            >
                <LinearLayout android:id="@+id/parent"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:orientation="horizontal"
                >
                </LinearLayout>
            </ScrollView>
        </RelativeLayout>
        

        tpl_yellow_brick.xml

        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_height="42dp"
            android:layout_width="42p"
        >
            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="I'm square yellow brick"            
            />
        </LinearLayout>
        

        java

        View brick = getLayoutInflater().inflate(R.layout.tpl_yellow_brick, null);
        ViewGroup parent = findViewById(R.id.parent);
        parent.addView(brick, 0);
        

        【讨论】:

          猜你喜欢
          • 2016-11-30
          • 1970-01-01
          • 1970-01-01
          • 2012-07-18
          • 1970-01-01
          • 2020-07-15
          • 1970-01-01
          • 2017-03-11
          • 2012-04-27
          相关资源
          最近更新 更多