I want to align text and an image in a LinearLayout
in the same line. I thought of using layout_gravity
option for the TextView
and ImageView
within a LinearLayout
with orientation=horizontal
but it doesn't seem to work. Any reason why is that?
Apparently, layout_gravity
works only with orientation=vertical
.
I can do it use multiple linear layouts within the main linear layout but was looking at an elegant way to do it.
Here is the code for the same:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center_horizontal"
android:background="#e3e2ad"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="24sp"
android:text="Layout's Vertical Orientation" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#bcf5b1"
android:layout_gravity="left"
android:text="left" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:src="@drawable/pigeon"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#d6c6cd"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="24sp"
android:text="Layout's Horizontal Orientation" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#bcf5b1"
android:layout_gravity="left"
android:text="left" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:src="@drawable/pigeon"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
I have already checked the answer to this question here but it didn't solve this problem. Difference between gravity and layout_gravity on Android