Search code examples
androidandroid-layoutandroid-relativelayout

Fitting ImageView elements on layout with multiple screen resolutions


I am new to android. I am trying to put 5 icons at the bottom of the screen. I have created icons of different resolutions i.e ldpi, mdpi, hdpi, xhdpi and xxhdpi. I am using the following layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/gameRootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.xx.drops.MainActivity" >

<RelativeLayout
    android:id="@+id/bucketLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginLeft="0dp"
    android:layout_marginBottom="25dp" >
</RelativeLayout>

</RelativeLayout>

enter image description here

I am adding the icons programatically into the child relative layout. But on devices with smaller screens, I am running into issue as mentioned in the image. In a device with screen 480*854, hdpi icons of size (96*96) are getting loaded but are going outside the screen. As per my understanding, if i can make it work on a proper size screen and provide icons of other resolutions, it should be taken care automatically. Please correct me if I am wrong. Can anyone help me solving this issue ?


Solution

  • You need to calculate the screen width first then set the width of each ImageView to screen width / 5 like the following:

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int screenWidth = size.x;
    int iconWidth = (int) screenWidth / 5;
    

    Then set the width of each ImageView to iconWidth.