2011-04-06 32 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作爲頂層佈局,然後設置兩個子佈局的權重。