Search code examples
androidandroid-relativelayout

Android how to allign these views


I am trying to allign two views in android layout.
I am having an ImageView

enter image description here

And I have to allign text in the middle of "popup" on the top.

Now my layout looks like:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/rl_authorization_main"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="top"
    android:padding="35dp"
    >

    <ImageView
        android:id="@+id/iv_map"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:adjustViewBounds="true"
        android:src="@drawable/map_contact"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_alignTop="@+id/iv_map"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:text="@string/address"
        android:textColor="@color/black"
        android:textSize="16sp"/>
</RelativeLayout>

But as you can see, android:layout_marginTop="20dp" of the TextView is hardcoded and it will not give desired result on all the devices.
I thought of using 9patch for this "popup", but it still will be the problem to point it into exact place on the map.

Should I somehow calculate the actual ImageView height and set layout_marginTop as a percent of actual height?


Solution

  • If the popup image is correctly scaled for all the resolutions, you can write android:layout_marginTop="20dp".

    Just follow the guidelines:

    • small: 1 dp = 0.5 pixels
    • medium: 1 dp = 1 pixel
    • large: 1 dp = 1.5 pixels
    • xlarge: 1 dp = 2 pixels
    • xxlarge: 1 dp = 3 pixels
    • xxxlarge: 1 dp = 4 pixels