2013-06-04 108 views
0

我有一些动态添加linearlayout的问题。它添加在屏幕的顶部,覆盖其他线性布局。Linearlayout覆盖另一个线性布局

这里是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); 

结果: enter link description here

感谢

回答

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)为true或0表示为false)。对于不涉及其他兄弟的动词(例如,ALIGN_WITH_PARENT_BOTTOM),只需使用-1。

+0

我试图做到这一点: RelativeLayout.LayoutParams PARAMS =新RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); params.addRule(RelativeLayout.ALIGN_BOTTOM,id_value_layout-1); hozLayout.setLayoutParams(params); 但情况是一样的。 – Postnik

0

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

+0

没有((我不知道LinearLayout的数量,可能是10或者可能是100. – Postnik

+0

那么,为什么不使用ListView,那么你的布局作为行,更容易编码。无论如何,如果你还想要以编程方式完成(这是不鼓励的,请参阅这里http:// stackoverflow。com/questions/9827819/best-practices-layouts-on-android-programmatic-vs-xml),然后像Ken Wolf所说的那样,将LinearLayout作为一个容器 –

1

请勿使用RelativeLayout作为持有人。改为使用LinearLayout而不是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