Search code examples
xmlbuttonlayoutscreen-size

Android xml-how to optimise layout for devices


I have made a simple layout but I am having trouble optimising it for different screen sizes. I have made it look fine on a 5.1 device but the buttons are to small on 10.1 and to big on a 3.2 screen. I have tried failed and been frustrated with many possibilities but can't seem to find any that work. Any ideas would be greatly appreciated thank you. Here is the code for my basic layout that look fine on a 5.1 inch screen.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Home" 
android:background="@drawable/bg">

<Button 
    android:id="@+id/playB"
    android:layout_width="300dp"
    android:layout_height="85dp"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true
    android:background="@drawable/menu_button"/>

<Button 
    android:id="@+id/aboutB"
    android:layout_alignLeft="@+id/playB"
    android:layout_below="@+id/playB"
    android:layout_marginTop="45dp"        
    android:layout_width="300dp"
    android:layout_height="85dp"
    android:layout_centerHorizontal="true"
    android:background="@drawable/menu_button"/>

<Button 
    android:id="@+id/settingsB"
    android:layout_alignLeft="@+id/playB"
    android:layout_below="@+id/aboutB"
    android:layout_marginTop="45dp"  
    android:layout_width="300dp"
    android:layout_height="85dp"
    android:layout_centerHorizontal="true"
    android:background="@drawable/menu_button"/>


Solution

  • Using dp is the right way. It wont be a constant size cuz AOS will scale dps using multiplier according to screen density. (btw dip==dp they are absolutely the same) so dps are density independent. However scaling is not enough usually. So you need to create separate resources for different screens and I might say that supporting multiple screens is a really very big pain in da @$$. Seems like the only one good and proper way is to use OpenGL...
    You might found following links helpful:
    How to use resource qualifier on layouts to distinguish smartphones like HTC Desire and Samsung Galaxy Nexus
    image size (drawable-hdpi/ldpi/mdpi/xhdpi)
    Avoid Multiple Drawable Sets (hdpi/mdpi/ldpi)
    Widget Layout for 960x540 and 854x480
    getDimension()/getDimensionPixelSize() - mutliplier issue
    http://www.findbestopensource.com/product/svg-android