Reputation: 89
I have TextView
and ImageButton
in xml
layout. And ImageButton
is positioned right of TextView
and I want group both to center them horizontally at screen. I use RelativeLayout
.
What should I do?
Upvotes: 3
Views: 14480
Reputation: 38098
An optimized approach, which doesn't use unnecessary layout nesting and reduces the View counts by incorporating the image inside the TextView:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
>
<TextView
android:id="@+id/headerText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true"
android:drawableRight="@drawable/ic_launcher"
android:text="@string/hello_world"
/>
</RelativeLayout>
The secret is the use of the compund drawable android:drawableRight="@drawable/ic_launcher"
.
To change it programmatically, use setCompoundDrawablesWithIntrinsicBounds()
Upvotes: 2
Reputation: 559
I assume you are developing an android application... If so this code can be used:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true"
android:orientation="horizontal">
<TextView
android:id="@+id/headerText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
/>
<ImageButton
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/ic_launcher" />
</LinearLayout>
</RelativeLayout>
android:layout_centerInParent="true"
will place items in the middle of the RelativeLayout
parent
android:layout_centerHorizontal="true"
will only center items horizontally. You can remove the one you don't need.
Upvotes: 3