Android中的Relativelayout

时间:2013-10-03 00:04:40

标签: android android-layout alignment relative

我正在为糖尿病患者制作一个Android应用程序。在那个应用程序中,我想显示食物项目的每餐用于饮食控制的数量。它看起来应该如下所示:

RICE          100gm
POTATO        50gm
FISH          60gm

这些信息将动态从我的数据库中获取。但是我正面临着安排它们的问题。我希望食物项目左对齐,数量在屏幕右侧对齐。如下(点表示屏幕)

|-------------------------------------------------------|
|RICE                                             100gm |
|POTATO                                            50gm |
|FISH                                              60gm |
|-------------------------------------------------------|

为此,我在xml文件中声明了一个相对布局。代码如下所示:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
    </RelativeLayout>

</LinearLayout>

现在我需要做的就是创建textview并动态地将它们添加到这个相对布局中。但我很困惑如何做到这一点。任何提示请...

最终输出应如下所示:

it should look something like below

1 个答案:

答案 0 :(得分:1)

我同意@Szymon,最好的方法是使用ListView。但是,如果您不想这样做,我会这样做:

  1. 为要显示的每个项目创建单独的布局。使其成为RelativeLayout,并根据您希望项目的显示方式将所有TextView放置在那里(alignParentRight / alignParentLeft)。

  2. 通过膨胀这个新布局动态创建视图,在运行期间膨胀的视图上使用findViewById()分配TextViews的文本

  3. 将视图添加到LinearLayout

  4. (编辑:如何做第2步:)

    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.my_item_layout, null);
    TextView tv1 = (TextView)view.findViewById(R.id.tv1);
    tv1.setText(myText);
    

    希望这会有所帮助:)

相关问题