Search code examples
androidandroid-layoutimageviewalpha-transparency

How can I overlay an ImageView with translucent views?


I have an ImageView in an activity that takes up the whole screen. What I want to do is have a few translucent buttons in the corner of this ImageView overlayed on top (like 30% transparency). Is this possible with an ImageView in android? If it is can someone point me in the right direction to get started?


Solution

  • Use a layout, and make your ImageView and two Buttons children within the layout.

    Example using RelativeLayout:

    <?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">
    
        <ImageView
                android:src="@drawable/image"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>
    
        <Button
                android:id="@+id/button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:alpha="0.5"
                android:text="Button 1"/>
    
        <Button
                android:id="@+id/button2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@id/button1"
                android:alpha="0.5"
                android:text="Button 2"/>
    
    </RelativeLayout>
    

    You can position your buttons better by using android:layout_marginTop and android:layout_marginLeft attributes.

    The key parts to understand here are:

    1/ The ImageView is set to match_parent, therefore it'll stretch to fill the RelativeLayout.

    2/ By default, sub Views are positioned at the top left of RelativeLayouts, this is why button1 appears there.

    3/ Button2 is positioned to the right of button1 using the RelativeLayout attribute layout_toRightOf. Its vertical position is still set to the default - top.