Textview没有在android中以编程方式显示在另一个textView的右边

时间:2012-08-17 06:31:21

标签: android textview relativelayout

我正在尝试动态地将textview添加到textView的右侧,但是没有显示textView。

以下代码中的语句“ params2.addRule(RelativeLayout.RIGHT_OF,1);”如果删除该行,则会在随机位置显示textview,从而产生问题。

需要动态实现此xml

<TextView
            android:id="@+id/stationnameVal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:text="KANYAKUMARI (CAPE)"
            android:textColor="@color/black"
            android:textSize="12sp" />

        <TextView
            android:id="@+id/arrivaltimeVal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="45dp"
            android:layout_toRightOf="@+id/stationnameVal"
            android:text="SRC"
            android:textColor="@color/black"
            android:textSize="12sp" />

代码是:

    RelativeLayout rel = new RelativeLayout(this);
    // first TextView
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);

        TextView stateName = new TextView(DisplayActivity.this);
        stateName.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
        params.setMargins(0, 5, 0, 0);
        stateName.setText("KANYAKUMARI (CAPE)");
        stateName.setId(1);
        stateName.setTextColor(R.color.black);
        stateName.setTextSize(12);
        rel.addView(stateName, params);

    // Adding Second TextView
       RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

       TextView arr = new TextView(DisplayActivity.this);
       arr.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
       arr.setText("SRC");
       arr.setTextColor(R.color.white);
       arr.setTextSize(12);
       params2.addRule(RelativeLayout.ALIGN_PARENT_TOP, stateName.getId());
       params2.addRule(RelativeLayout.RIGHT_OF, 1);
       params2.setMargins(45, 0, 0, 0);
       rel.addView(arr, params2);

2 个答案:

答案 0 :(得分:1)

如何将“LayoutParams.FILL_PARENT”更改为“LayoutParams.WRAP_CONTENT”?

此致

陈子腾

答案 1 :(得分:1)

改变这个:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

或者这个:

rel.addView(stateName, params);

rel.addView(stateName);

也改变了这个:

params2.addRule(RelativeLayout.ALIGN_PARENT_TOP, stateName.getId());

params2.addRule(RelativeLayout.ALIGN_PARENT_TOP);

为param做同样的事情:

params.addRule(RelativeLayout.ALIGN_PARENT_TOP);

否则将其删除,因为Kanyakumari和src未正确对齐。

实际上这样做是为了对齐它们:

params2.addRule(RelativeLayout.ALIGN_TOP, 1);