2011-04-06 24 views
1

我想在我的UI初始化中将LinearLayout的宽度设置为屏幕宽度的一半动态。我有LinearLayout周围RelativeLayout包裹,层次结构如下:使用View代替Layout如何在运行时缩放Android布局对象?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:orientation="vertical" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" > 

     <LinearLayout 
      android:id="@+id/left_linear_layout" 
      android:layout_alignParentLeft="true" 
      android:layout_height="fill_parent" 
      android:layout_width="155dp" <!--want to set this to 1/2 screen width--> 
      android:orientation="vertical"> 
      ... 
     </LinearLayout> 
     <LinearLayout 
      android:id="@+id/right_linear_layout" 
      android:layout_alignParentRight="true" 
      android:layout_height="fill_parent" 
      android:layout_width="385dp"><!--want to set this relative to screen width as well--> 
      .... 
     </LinearLayout> 
</RelativeLayout> 

或者,可以在此问题得到解决?任何建议表示赞赏!

回答

0

您可以通过使用layout_weight来完成此操作,但是您需要添加一些不可见的视图来填充。例如,下面将让你的顶部面板半个屏幕宽度:

<RelativeLayout 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    xmlns:android="http://schemas.android.com/apk/res/android"> 
     <LinearLayout 
        android:id="@+id/left_linear_layout" 
        android:layout_alignParentLeft="true" 
        android:layout_height="fill_parent" 
        android:layout_width="0dp" 
        android:layout_weight="1" 
        android:orientation="vertical" 
        > 
      ... 
     </LinearLayout> 
     <!-- need this view to fill the other half of the screen --> 
     <View 
        android:id="@+id/spacer" 
        android:layout_toRightOf="@id/left_linear_layout" 
        android:layout_height="fill_parent" 
        android:layout_width="0dp" 
        android:layout_weight="1" 
        /> 

    .... 
</RelativeLayout> 

每个视图将占用量layout_weight/total_layout_weight。在这种情况下,total_layout_weight = 1+1 = 2和每个视图的layout_weight为1,因此每个视图占用屏幕的1/2

0

您可以简单地使用LinearLayout作为顶层布局,然后设置两个子布局的权重。