View ignores alpha value after View.VISIBLE

Viewed 1808

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.

3 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);
        }
    }
}
Related