Reputation: 2480
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.
Upvotes: 11
Views: 2483
Reputation: 7283
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);
}
}
}
Upvotes: 23
Reputation: 1932
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.
Upvotes: 1
Reputation: 5011
After setting Button
Gone
to Visible
, add Alpha of the Button
like :
buttonObject.setAlpha(.5f);
Upvotes: 0