简体   繁体   中英

How to center a fixed sized main layout in android?

I want my layout to be fixed sized say: 320dp by 480dp as a default for ldpi screen resolution.

So when the user has a 720x1280 device the layout would still be 320x480 but would be centered.

Any suggestions? I want to avoid creating multiple layouts for each resolution.

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <RelativeLayout android:layout_width="320px"
        android:layout_height="480px"
        android:layout_centerInParent="true"
        android:background="@color/white">

    </RelativeLayout>

</RelativeLayout>

Hope this is what you want.

For your parent view container, you should just set the layout_width and layout_height to the desired size and then make its layout_gravity equal to center. So, in your case you would use the following

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="320dp"
    android:layout_height="480dp"
    android:layout_gravity="center" >

    <!-- The rest of your layout -->

</LinearLayout>

That should center the view and keep it the desired size. It should be noted that you can use any layout, not just LinearLayout.

Hope this helps! Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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