视图在View.VISIBLE之后忽略alpha值

BVt*_*Vtp 2 android alpha view button

我有一个按钮,alpha设置为0.5,其可见性在布局中消失了.

 <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"/>
Run Code Online (Sandbox Code Playgroud)

在某些时候,我希望让它可见(Button.setVisibility(View.VISIBLE);),但是当我这样做时 - 它不是半透明的(0.5).看起来好像alpha设置为1.

Sir*_*lot 6

此问题通常android:animateLayoutChanges="true"是父视图中的结果.原因是设置可见性的布局动画也会更改视图的alpha并覆盖所做的更改setAlpha.

要解决此问题,您可以android:animateLayoutChanges="true"从父项中删除或创建自定义视图以设置可见性,onVisibilityChanged如下所示:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这就是为我做的,取出了'android:animateLayoutChanges ="true"`因为它因某种原因将alpha设置为1. (2认同)

Say*_*yem 0

设置为 后Button GoneVisible添加 AlphaButton

喜欢 :

buttonObject.setAlpha(.5f);
Run Code Online (Sandbox Code Playgroud)