相对于其他元素进行布局(而不是RelativeLayout)

本文关键字:RelativeLayout 布局 其他 元素 相对于 | 更新日期: 2023-09-27 18:19:25

是否可以使用其他元素值的百分比来设置高度、宽度和边距等值。例如,一个元素的宽度是另一个元素宽度的一半。

我不在乎这是在编程上还是在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;
}

相对于其他元素进行布局(而不是RelativeLayout)

一种方法是在线性布局中使用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>

关于这方面的更多信息可以在这里的文章中找到。