Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View ignores alpha value after View.VISIBLE

I have a button ,with alpha set to 0.5, and its visibility is gone in the layout.

 <Button
     android:id="@+id/Button"
     android:layout_width="match_parent"
     android:layout_height="50dp"
     android:background="@color/black_color" 
     android:alpha="0.5"
     android:visibility="gone"/>

At some point, I wish to make it visible ( Button.setVisibility(View.VISIBLE); ), but when I do - it's not half-transparent (0.5). It appears as if alpha is set to 1.

like image 649
BVtp Avatar asked Mar 07 '16 09:03

BVtp


2 Answers

This problem is usually the result of having android:animateLayoutChanges="true" in the parent view. The reason is that the layout animation of setting visibility also changes the alpha of the view and overrides the change made by setAlpha.

To resolve this you can either remove android:animateLayoutChanges="true" from the parent or create a custom view to set the visibility in onVisibilityChanged like this:

public class AlphaView extends View {

    private static final String TAG = AlphaView.class.getSimpleName();

    public AlphaView(Context context) {
        super(context);
    }

    public AlphaView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public AlphaView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public AlphaView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onVisibilityChanged(@NonNull View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);

        if (visibility == VISIBLE) {
            setAlpha(0.5f);
        }
    }
}
like image 182
Sir Codesalot Avatar answered Oct 05 '22 15:10

Sir Codesalot


I ran into this problem as well. It seems to be a bug in Android itself. My solution was to avoid setting visibility, and to adjust alpha only. My view has a visibility of 'visible' in the XML, and starts off with the XML alpha tag value set to 0.0. Then, when I want it to be visible, I adjust the alpha programmatically:

        dimmerView.setAlpha(.15f);

I disappear it by setting the alpha again to zero. Theoretically, you might need to adjust various views position on the z-axis with bringToFront (and in the case of a button you might want to remove its listener when alpha is set to zero), but in my implementation it did not seem to be necessary.

like image 37
Casey Perkins Avatar answered Oct 05 '22 13:10

Casey Perkins