简述现象
项目里发现有时候一些页面设置的白色背景会突然没有,没有找到复现步骤。一旦出现就很难恢复,也没有找到复现步骤。
后来发现是因为某些页面里对一个view这样操作导致:
bg.getBackground().setAlpha(0);
但出现的前提是,这个对应的bg是在xml里设置的背景color,且背景color值和受影响的页面color值相同。比如我们的项目里出问题的都是白色背景,都是在xml里这样设置:
android:background="@color/white"
解决办法
对需要设置alpha变化的view,不在xml写android:background="@color/white"。
而是在需要用到alpha变化之前设置:
bar.setBackgroundColor(getResources().getColor(R.color.white));
bar.getBackground().setAlpha(0);
验证实验
第一个Activity设置一个蓝色的背景:
点击中间按钮进入Activity B。Activity B的layout xml里设置了相同的蓝色背景:
点击Activity B的按钮改变背景色的alpha:
baseView.getBackground().setAlpha(0);
退出Activity B,返回Activity A发现背景也没了。
进一步试验,在Activity B调用setAlpha(100),返回Activity A,背景的变化也是一样的:
返回后背景一样是半透明的蓝色:
最后
这个问题,测试发现,华为,小米,OV都一致。所以应该是android系统本身的设计导致。
附
Activity A布局xml源码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/blue"
tools:context=".MainActivity">
<Button
android:id="@+id/bg_alpha"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="bg alpha" />
</LinearLayout>
Activity B布局xml源码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/base_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/blue"
android:orientation="vertical"
tools:context=".BgAlphaActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Activity B" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="click to change" />
</LinearLayout>
Activity B改变背景alpha源码:
public class BgAlphaActivity extends AppCompatActivity {
private View baseView;
private int a = 25;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bg_alpha);
baseView = findViewById(R.id.base_layout);
baseView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setAlpha(v);
}
});
}
public void setAlpha(View view) {
if (++a > 25) {
a = 0;
}
baseView.getBackground().setAlpha(a*10);
}
}