Boldijar Paul
Boldijar Paul

Reputation: 5495

Android centering an textview next to a imageview

I have an imageview and i want to put in the right a textview, but that will stay centered verticaly, so I can make my custom listview.

This photo can explain better: enter image description here

My code

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

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/icon1" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/imageView1"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

Upvotes: 1

Views: 108

Answers (1)

Phant&#244;maxx
Phant&#244;maxx

Reputation: 38098

Set your TextView's attribute

android:layout_centerVertical="true"

It would be even better if you set your image as a compound drawable inside the TextView (to the left of it):

android:drawableLeft="@drawable/icon1"
android:drawablePadding="8dp"

The two lines above are in the TextView definition and completely replace your ImageView.
This is a best practice and increases the overall performance, by flattening your layout hierarchy.

And remove the android:gravity="top" attribute in the parent.
Also, to make this the item row of a ListView, this android:layout_height="match_parent" should be android:layout_height="wrap_content"

Upvotes: 1

Related Questions