Align ImageView with EditText horizontally

2020-02-26 12:36发布

I'm trying hard to find a way of aligning an EditText and an ImageView properly on Android. I keep getting this result:

enter image description here

The XML part is quite simple:

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

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:scaleType="centerInside"
        android:src="@drawable/android"
        android:visibility="gone" />

    <EditText
        android:id="@+id/edittext"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:singleLine="true" />

</LinearLayout>

I've also tried many of the suggestions below, including PravinCG's (RelativeLayout with alignTop/alignBottom):

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/edittext"
        android:layout_alignTop="@+id/edittext"
        android:scaleType="centerInside"
        android:src="@drawable/android"
        android:visibility="visible" />

    <EditText
        android:id="@+id/edittext"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/image"
        android:hint="@string/username"
        android:singleLine="true" />

</RelativeLayout>

But the result is exactly the same.

I've tried playing with the EditText's background padding, intrinsic height, but to no avail.

The EditText's background drawable is different among Android versions/ROMs, and I want to support them all.

How can I make this alignment pixel perfect on any android version (and style)?

7条回答
相关推荐>>
2楼-- · 2020-02-26 13:19

I used a quick workaround by simply moving the EditText down 2dp by simply adding the following to the EditText:

android:layout_marginBottom="-2dp"
android:layout_marginTop="2dp"
查看更多
登录 后发表回答