Search code examples
androidandroid-layoutimageviewandroid-linearlayoutandroid-relativelayout

Center an imageview in half of parentview without using LinearLayout


The way my layout is designed at the moment is that I have a LinearLayout having a width="match_parent". This view has two ImageViews as its children, which take up half of the LinearLayouts width using weight="1"

The problem is that this way, onClicks are registered on transparent portions of the card, because the View is stretched.

Edit: I should have mentioned, that these circles are only supposed to represent image files and not circle-shapes filled with a solid color.

My current code:

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

    <ImageView

        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <ImageView

        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

</LinearLayout>

The red portion indicates touch areas

x

what I want is something like the following while keeping the ratios: this

I know that I could simply try to nest each ImageView in a RelativeLayout like so:

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

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1">

        <ImageView
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1">

        <ImageView
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </RelativeLayout>


</LinearLayout>

but nesting like this is pretty horrible form


Solution

  • use percentage relative layout no nesting required link here