以编程方式在布局中布置子视图

时间:2011-08-20 19:26:36

标签: android android-layout relativelayout

我正在尝试在平板电脑上以相对布局布局视图,就像书架一样。将会有这么多,然后创建一个新行。

我的初始状态如下:

  <ScrollView
    android:layout_marginTop="150sp"
    android:layout_marginLeft="50sp"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <RelativeLayout
      android:id="@+id/user_list"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content">

      <!-- Add User Avatar -->
        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <ImageView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:src="@drawable/user_frame" />
            <ImageView
                android:id="@+id/demo_image"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:src="@drawable/add_user"
                android:layout_marginLeft="10px" />
            <ImageView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:src="@drawable/user_name_background"
                android:layout_marginLeft="10px" />
            <TextView
                android:id="@+id/user_name"
                android:layout_width="180px"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                android:textStyle="bold"
                android:gravity="center_horizontal"
                android:text="Add New User" />
        </RelativeLayout>

      </RelativeLayout>
  </ScrollView>

我正在从数据库中获取记录,对于每条记录,我需要放置一个版本的“添加用户头像”部分,如上所示。我想做5,然后换成新的一行。

我最初的想法是使用布局inflater并以编程方式添加视图,使用RelativeLayout.LayoutParams设置layout_toRightOf值。

必须有一种更简单的方法。我见过许多使用“书架”比喻的应用程序。

2 个答案:

答案 0 :(得分:3)

我可以想到几个选项。

  1. 为什么不使用LinearLayouts和水平属性?
  2. ,而不是使用相对布局
  3. 使用TableLayout,非常类似于LinearLayout
  4. 使用带有自定义适配器的ListView为每个ListRow填充五个“添加用户头像”

答案 1 :(得分:3)

以编程方式布置视图非常简单。我为我的所有活动/观点做了这个。我喜欢Android的XML布局概念,但发现只要视图根据外部数据(例如您的数据库)变得完全动态,它就会变得太复杂。

我选择最外层布局,然后仅在XML中实例化该布局。然后在我的活动中,我使用id调用的常规find找到外部布局,然后使用一系列add(View)方法调用来根据需要添加我动态创建的视图或布局。

您需要考虑不同的屏幕方向,像素密度和大小。设备无关像素将成为您的朋友。例如,要创建图像视图,您可以加载位图,计算调整大小的位置(如果需要),然后将其设置为新ImageView实例的drawable,然后将其添加到布局中。

听起来你的外部布局是一个内部有垂直线性布局的滚动视图,然后每个“架子”都有一个水平布局,每个“书”最多有五个图像视图

相关问题