Search code examples
androidandroid-layoutandroid-screen-support

ImageView margins for different screen sizes


How can I set margins(Left,Top,Right,Bottom) to these ImageView so that it will display correctly on multiple screen sizes in Android ? Also I need to handle click events on these Images.1


Solution

  • Well the whole point of using DP is so that you don't have to worry about this. Margins will be roughly the same across devices, but if you're relying on lining things up on one particular device resolution/density combination, you'll definitely be in for a surprise when you test on other devices.

    That said, if you do need to specify different margins for different screen sizes, simply add an XML file in res/values -- something like dimens.xml:

    <resources
        xmlns:android="http://schemas.android.com/apk/res/android"
        >
        <dimen name="my_view_margin">10dip</dimen>
    </resources>
    

    Then add one of these XMLs for every specific device qualifier that you need to (e.g. values-large, values-sw600dp, values-xlarge, etc.) and modify the value as you see fit. When you want to use these dimensions in a layout, just use:

    android:layout_margin="@dimen/my_view_margin"
    

    And Android will pick the correct value for whatever device it happens to be running on.