Home » Android » java – How can I align my ImageView with my TextView in a LinearLayout?

java – How can I align my ImageView with my TextView in a LinearLayout?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have the following ImageView and TextView:
enter image description here

Here is the XML:

<LinearLayout android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/headerLinearLay" android:orientation="horizontal">
        <ImageView android:src="@drawable/icon" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/avatarImageView"></ImageView>
        <TextView android:layout_height="wrap_content" android:id="@+id/usernameTextView" android:text="TextView" android:layout_width="wrap_content" android:paddingLeft="4px"></TextView>
    </LinearLayout>

How can I make the image and the text be positioned at the same height? I also want the ImageView to be in the corner

How to&Answers:

Try this:

<RelativeLayout
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:id="@+id/headerLinearLay">
    <ImageView
        android:id="@+id/avatarImageView"
        android:src="@drawable/icon"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"></ImageView>
    <TextView
        android:id="@+id/usernameTextView"
        android:text="TextView"
        android:paddingLeft="4dp"
        android:layout_toRightOf="@id/avatarImageView"
        android:layout_centerVertical="true"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"></TextView>
</RelativeLayout>

Answer:

Here is a simple solution that works well. Essential here is to add: android:layout_gravity=”center_vertical” to TextView

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/icon" />

    <TextView
        android:id="@+id/usernameTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical" />

    </LinearLayout>

Answer:

<TextView
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="TextView"
    android:layout_weight="0.04" />

<ImageView
    android:id="@+id/imageView"
    android:layout_width="204dp"
    android:layout_height="200dp"
    app:srcCompat="@mipmap/ic_launcher" />