Search code examples
androidlayouttextviewdensity-independent-pixel

Why buttons has the same size on multiple screens (Android 1.6+)?


Please help me with one problem. When I change min sdk version from 3 (Android 1.5) to 4 (1.6) or higher, all buttons and textviews have the same size on multiple screens although I use dp and sp units. Why might this be?

Simple example (main.xml):

<?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"
>
    <Button 
        android:id="@+id/button"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:text="OK"
        android:layout_centerInParent="true"
    />
</LinearLayout>

Screenshot from Google Nexus 7: http://s019.radikal.ru/i601/1312/fd/e769f6e3a690.png

Screenshot from Sony Ericsson Xperia Play: http://s019.radikal.ru/i600/1312/9d/6b3f580e7503.png


Solution

  • Create dimen.xml for following folder as per your requirement:

    1. values
    2. values-hdpi
    3. values-ldpi
    4. values-mdpi
    5. values-sw600dp
    6. values-sw720dp-land etc...

    and code for that dimen.xml and give xxxdp as you want:

    <resources>
    
        <!-- Default screen margins, per the Android Design guidelines. -->
        <dimen name="button_width">300dp</dimen>
        <dimen name="button_height">300dp</dimen>
    
    </resources>
    

    then after you xml file like:

    <?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">
        <Button 
            android:id="@+id/button"
            android:layout_width="@dimen/button_width"
            android:layout_height="@dimen/button_height"
            android:text="OK"
            android:layout_centerInParent="true" />
    </LinearLayout>
    

    FOR PROGRAMMATICALLY:

    This also works:

    getResources().getDisplayMetrics().density;
    

    This will give you:

    • 0.75 - ldpi
    • 1.0 - mdpi
    • 1.5 - hdpi
    • 2.0 - xhdpi
    • 3.0 - xxhdpi
    • 4.0 - xxxhdpi

    May it'll be Helpful...

    Thanks...