Search code examples
androidimageviewandroid-relativelayout

How to place ImageButton over ImageView in RelativeLayout


enter image description here

I'd like to do this in my RelativeLayout with two ImageButtons and an ImageView. Is it possible to do this without using marginTop? Any responses are welcomed. My xml code:

        <ImageView 
       android:id="@+id/imageview"
       android:layout_width="match_parent"
       android:layout_height="150dp"
       android:scaleType="fitXY"
       android:layout_alignParentBottom = "true"
       android:src="@drawable/image1"/>

   <ImageButton
       android:id="@+id/imagebutton1"
       android:layout_width="70dp"
       android:layout_height="50dp"
       android:scaleType="fitXY"
       android:layout_alignParentRight="true"
       android:layout_alignParentBottom = "true"
       android:background="@drawable/image2"/>

      <ImageButton
       android:id="@+id/imagebutton2"
       android:layout_width="70dp"
       android:layout_height="50dp"
       android:scaleType="fitXY"
       android:layout_alignParentLeft="true"
       android:layout_alignParentBottom = "true"
       android:background="@drawable/image3"/>

Solution

  • RelativeLayouts are almost always the right layout, they are very powerful. In your case, you can simply use 'android:layout_centerVertical="true"', but get rid of the 'layout_alignParentBottom'

    <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="150dp">
        <ImageView
                android:id="@+id/imageview"
                android:layout_width="match_parent"
                android:layout_height="150dp"
                android:scaleType="fitXY"
                android:layout_alignParentBottom = "true"
                android:src="@drawable/image1"/>
    
        <ImageButton
                android:id="@+id/imagebutton1"
                android:layout_width="70dp"
                android:layout_height="50dp"
                android:scaleType="fitXY"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:background="@drawable/image2"/>
    
        <ImageButton
                android:id="@+id/imagebutton2"
                android:layout_width="70dp"
                android:layout_height="50dp"
                android:scaleType="fitXY"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:background="@drawable/image3"/>
    </RelativeLayout>
    

    In my personal experience: when in doubt, use RelativeLayout.