繁体   English   中英

如何设置宽度和高度的权重?

[英]How to set weight for width and height?

我需要创建具有宽度和高度的动态视图,它们是父尺寸的百分比。所以我需要为一个视图添加宽度和高度的重量。 是否可以?

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:weightSum="4"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="80dp"
        android:layout_weight="1"
        android:gravity="center"
        android:id="@+id/imgtype"
        android:scaleType="fitCenter"/>

     <TextView
        android:layout_width="0dp"
        android:layout_height="80dp"
        android:layout_weight="3"
        android:id="@+id/txtsubject"
        android:textStyle="bold"
        android:textSize="@dimen/lat_sub_text_size"
        android:textColor="@android:color/black"/>
<LinearLayout/>

在这里,您将能够将父线性布局宽度的主要部分划分为文本视图,剩余的次要部分用于图像视图,这用于水平对齐,垂直对齐也可以。父项的权重属性决定了它将包含的部分数量。

例如,我有以下布局:

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/ll_forImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />    
    </LinearLayout>
    <LinearLayout
        android:id="@+id/ll_forList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </ListView>    
    </LinearLayout>
</LinearLayout>

现在,我将根据屏幕宽度和屏幕高度为每个视图设置宽度和高度。

int screenWidth = dpToPx(getResources().getConfiguration().screenWidthDp);
int screenHeight = dpToPx(getResources().getConfiguration().screenHeightDp);
int ratioW = ....;//
int ratioH = ....;//
setLayoutSize(ll_forImage, screenWidth/ratioW , screenHeight/ratioH );
setLayoutSize(ll_forList, screenWidth/ratioW , screenHeight - screenHeight/ratioH );
// You can use setTranslation to translate View to expected position.

和:

private int dpToPx(int dp) {
    return (int) (dp * getResources().getDisplayMetrics().density + 0.5f);
}

private static void setLayoutSize(View view, int width, int height) {
    ViewGroup.LayoutParams params = view.getLayoutParams();
    params.width = width;
    params.height = height;
    view.setLayoutParams(params);
}

在使用 LinearLayout 时添加 layout_weight 是一个很好的方法。 请记住,layout_weight 仅适用于 LinearLayout,不能与 RelativeLayout 一起使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM