joynes
joynes

Reputation: 1647

Set alpha on ImageView without setAlpha

Can I programatically set the alpha of an ImageView without the need for being dependent on API level 11 where setAlpha was introduced?

Upvotes: 9

Views: 21375

Answers (4)

Kees Koenen
Kees Koenen

Reputation: 770

I used code to setAlpha of the image itself, not the view. This is available from API level 1..

public void toggleButton(int i) {
    if (indImageBtnEnabled[i]) {

        int di = getDrawableId(findViewById(myImagebtns[i]));
        Drawable d = this.getResources().getDrawable(di);
        d.setAlpha(25);

        ((ImageView) findViewById(myImagebtns[i])).setImageDrawable(d);

        indImageBtnEnabled[i] = false;
    } else {
        // findViewById(myImagebtns[i]).setAlpha(1f) << NEEDS API11;
        int di = getDrawableId(findViewById(myImagebtns[i]));
        Drawable d = this.getResources().getDrawable(di);
        d.setAlpha(255);

        ((ImageView) findViewById(myImagebtns[i])).setImageDrawable(d);

        indImageBtnEnabled[i] = true;
    }
}

Upvotes: 4

NBApps
NBApps

Reputation: 521

you can make a new layout with just ur image, set the alpha you need for the layout, set it as an overlay and inflate when you want.

LayoutInflater inflater = LayoutInflater.from(this);
        View overView = inflater.inflate(R.layout.myAlpahImageLayout, null);
        this.addContentView(overView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:alpha="0.5"
    tools:context=".MainActivity" >

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

</RelativeLayout>

Upvotes: 2

Muhammad Nabeel Arif
Muhammad Nabeel Arif

Reputation: 19310

ImageView has a method setAlpha(int) since API leve 1. So you can use it in any API level.
It is the setAlpha(float) method of View which is introduced in API level 11.

Upvotes: 40

FoamyGuy
FoamyGuy

Reputation: 46856

I think (But don't know for sure) that you could apply an alpha animation to your ImageView, and as long as the fillAfter() is set to true on the animation the Image should stay at whatever alpha level it ends at.

Upvotes: 2

Related Questions