制作RelativeLayout视图

时间:2014-04-22 08:01:19

标签: android android-layout

我是Android的新手,所以我花了几个小时试图在代码中看起来像这样。有人可以帮忙吗? enter image description here

这是我的尝试:

RelativeLayout photo = new RelativeLayout(this);
        photo.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, densityToPixels(80)));
        photo.setGravity(Gravity.CENTER_VERTICAL);

        allphotos.addView(photo);

        TextView textView1 = new TextView(this);
        textView1.setLayoutParams(new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        textView1.setGravity(Gravity.CENTER_VERTICAL);
        textView1.setText("IDasdfasdfasdfasdfasdfd");

        photo.addView(textView1);

        RelativeLayout.LayoutParams params = 
                new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);

        ImageView img = new ImageView(this);
        img.setLayoutParams(new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        img.setLayoutParams(params);
        photo.addView(img);

        ImageView del_img = new ImageView(this);
        img.setLayoutParams(new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        img.setLayoutParams(params);
        photo.addView(del_img);

2 个答案:

答案 0 :(得分:1)

为什么要在代码中完成所有操作?使用xml。如果你需要从xml构造的视图,请使用View.inflate将xml传递给它。

答案 1 :(得分:1)

在代码中真的没有必要这样做。
只需使用TextView并向其添加两个复合drawable:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <TextView
        android:id="@+id/txtText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:padding="8dp"
        android:textSize="14sp"
        android:textColor="@color/white"
        android:drawableLeft="@drawable/icon_left"
        android:drawableRight="@drawable/icon_rite"
        android:drawablePadding="8dp"
    />
</RelativeLayout>

<强> [编辑]

在代码中设置化合物:

1 - 您不再需要TextView定义中的这些行:

        android:drawableLeft="@drawable/icon_left"
        android:drawableRight="@drawable/icon_rite"

2 - 您需要在代码中设置drawable:

// given that you retrieved your TextView as txt and you retrieved your drawables as drwLeft and drwRite
// Parameter order: left, top, right, bottom 
txt.setCompoundDrawablesWithIntrinsicBounds(drwLeft, null, drwRite, null);