2013-06-20 21 views
0

是否可以通過使用另一個元素的值的百分比來設置諸如高度,寬度和邊距之類的值。例如,有一個元素的寬度是另一個元素的寬度。相對於其他元素(不是RelativeLayout)鋪設事物

我不會爲這是編程式還是在axml代碼而煩惱。

目前我一直在試圖做到這一點編程方式是這樣的:

protected override void OnCreate (Bundle bundle) 
{ 
    base.OnCreate (bundle); 

    var metrics = Resources.DisplayMetrics; 
    var widthInDp = ConvertPixelsToDp(metrics.WidthPixels); 
    var heightInDp = ConvertPixelsToDp(metrics.HeightPixels); 

    SetContentView (Resource.Layout.Main); 

       //Set title width as 98% of total width 
    ImageView title_img = FindViewById<ImageView> (Resource.Id.apptitle); 
    LinearLayout baseparent = FindViewById<LinearLayout> (Resource.Id.baselayout); 
    title_img.LayoutParameters.Width = (baseparent.Width/100) * 98 ; 
       //Set welcome width as half of title width 
    ImageView welcome_img = FindViewById<ImageView> (Resource.Id.welcome); 
    welcome_img.LayoutParameters.Width = title_img.Width/2; 
} 


private int ConvertPixelsToDp(float pixelValue) 
{ 
    var dp = (int) ((pixelValue)/Resources.DisplayMetrics.Density); 
    return dp; 
} 
+0

您發佈的代碼對我來說似乎是完全正確的。你能解釋爲什麼代碼不起作用嗎?或者它是做錯了? – jHogen

回答

0

一種方法做,這是使用android:layout_weight參數的線性佈局。例如有一個元素兩倍大,第二個你可以這樣做:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <LinearLayout android:background="#FF0000" 
     android:layout_height="fill_parent" android:layout_width="fill_parent" 
     android:layout_weight="2" /> 
    <LinearLayout android:background="#00FF00" 
     android:layout_height="fill_parent" android:layout_width="fill_parent" 
     android:layout_weight="1" /> 
</LinearLayout> 

多一點關於這個可以在article here找到。

相關問題