设置视图背景的不透明度的正确时机是什么

问题描述 投票:1回答:1

我尝试设置自定义linearLayout的背景alpha。

我试过了:

//ctor
protected MyView(
      Context context, AttributeSet attrs, int defStyle, @LayoutRes int layout) {
    super(context, attrs, defStyle);
    setOrientation(VERTICAL);
    LayoutInflater.from(context).inflate(layout, this);
        getBackground().setAlpha(128);

}

vto.addOnGlobalLayoutListener(
    new OnGlobalLayoutListener() {
      @Override
      public void onGlobalLayout() {
        getViewTreeObserver().removeOnGlobalLayoutListener(this);
        getBackground().setAlpha(128);
      }
    });

但背景仍然是空的

我试过了

ViewTreeObserver vto = getViewTreeObserver();
vto.addOnPreDrawListener(new OnPreDrawListener() {
  @Override
  public boolean onPreDraw() {
    vto.removeOnPreDrawListener(this);
    getBackground().setAlpha(128);

    return true;
  }
});

但我得到java.lang.IllegalStateException: This ViewTreeObserver is not alive, call getViewTreeObserver() again

获取背景并更改其alpha(不透明度)的正确时机是什么?

android view android-linearlayout opacity alpha
1个回答
0
投票

您是否在xml中尝试了android:alpha =“0.5”属性作为线性布局?

© www.soinside.com 2019 - 2024. All rights reserved.