bigjoe1 bigjoe1 - 1 month ago 7
Android Question

Placing elements in horizontal layout (android)

I want to place ImageView on the center of screen and ImageButton on the right of that ImageView, see
Screen.

How can I do this? I tried horizontal linear layout and gravity: center but both elements are on center.

Thanks in advance :)

Answer

The idea is to use RelativeLayout. Set you ImageView in center of parent. Then put the imageButton on the right of it. see my example:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    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"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff00ff00"
        android:text="text1"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ffff0000">

        <ImageView
            android:id="@+id/main_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:src="@drawable/ic_done_white_24px"
            />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/main_image"
            android:src="@drawable/ic_account_box_black_24dp"
            />

    </RelativeLayout>

    <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff00ff00"
        android:gravity="center_vertical"
        android:text="text2"/>

</LinearLayout>

Output:

Comments