Search code examples
androidviewheightwidthandroid-layout-weight

How to set weight for width and height?


I need to create view dynamical with width and height which are the percent of parent size.So I need to add weight for width and height for one view. Is it possible?


Solution

  • For example, I have the below layout:

    <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>
    

    Now, I will set width and height for each View depend on Screen width and Screen Height.

    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.
    

    with:

    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);
    }