0

我在动态添加线性布局时遇到了一些问题。它添加在屏幕顶部,覆盖其他线性布局。

这里是 XML、代码和结果。

XML:

<TextView
    android:id="@+id/top_km"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:background="#888"
    android:gravity="top"
    android:textColor="#fff"
    android:textSize="30dip"
    android:layout_centerHorizontal="true"/>

<RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/top_km"
        android:id="@id/textLayout">

</RelativeLayout>

代码:

myLayout = (RelativeLayout) page.findViewById(R.id.textLayout);
LinearLayout linLayout = new LinearLayout(this);  
linLayout.setOrientation(LinearLayout.VERTICAL);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
myLayout.addView(linLayout);
LinearLayout hozLayout = new LinearLayout(this);
hozLayout.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
myLayout.addView(hozLayout);

结果: 在此处输入链接描述

谢谢

4

3 回答 3

2

不要使用 aRelativeLayout作为您的持有人。改用LinearLayoutwith orientation="vertical"

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_below="@+id/top_km"
    android:orientation="vertical"
    android:id="@id/textLayout" />

然后在代码中

myLayout = (LinearLayout) page.findViewById(R.id.textLayout);

其次是

// rest of your code
于 2013-06-04T17:34:30.850 回答
1

这是因为您使用RealativeLayout来正确添加使用 1.RelativeLayout.LayoutParams 用于 st LayoutParams 2.在 LayoutParams 中使用下面的字段

例子:

RelativeLayout rl=new RelativeLayout(this);
LinearLayout ll1=new LinearLayout(this);
TextView tx1=new TextView(this);
tx1.setText("Test1");
ll1.addView(tx1);
rl.addView(ll1);
LinearLayout ll2=new LinearLayout(this);
TextView tx2=new TextView(this);
tx2.setText("Test1");
ll2.addView(tx1);
rl.addView(ll2);
RelativeLayout.LayoutParams lp2=(LayoutParams) ll2.getLayoutParams();

然后使用lp2.addRule

这里有一些帮助:

参数 verb 由 RelativeLayout 定义的动词之一,例如 ALIGN_WITH_PARENT_LEFT。anchor 另一个视图的 id 用作锚点,或布尔值(表示为 TRUE)表示真或 0 表示假)。对于不引用另一个兄弟的动词(例如,ALIGN_WITH_PARENT_BOTTOM),只需使用-1。

于 2013-06-04T17:18:50.070 回答
0

也许您更容易将它添加到 XML 文件中android:visibility="GONE",然后在代码中显示它 ( View.VISIBLE) 或隐藏它 ( View.GONE)。

于 2013-06-04T17:19:12.223 回答