getBackground().setAlpha所导致问题

来源:互联网 发布:端口被系统占用 编辑:程序博客网 时间:2024/06/04 18:35

在项目中遇到一个问题,用framelayout装载三个Fragment,每个fragment都有一个titleBar,每个titlebar的背景颜色一样,我想在第一个fragemnt中设置titlebar的透明度为50,于是我是这样设置的:

mTitlebar.getBackground.setAlpha(50);

那么问题来了,运行项目,发现每个三个titleBar的背景都改变了。
于是乎,运用强大的百度一下,终于解决了这个问题,看来看源码很重要啊。。。。
解决办法:

mTitlebar.getBackground().mutate().setAlpha(50);

那为什么呢:默认情况下,所有的从同一资源(R.drawable.*等等)加载的实例都共享一个共用的状态,如果你更改一个实例的状态,其余的实例都会接收到相同的通知。

查看这个方法:

/** * Make this drawable mutable. This operation cannot be reversed. A mutable * drawable is guaranteed to not share its state with any other drawable. * This is especially useful when you need to modify properties of drawables * loaded from resources. By default, all drawables instances loaded from * the same resource share a common state; if you modify the state of one * instance, all the other instances will receive the same modification. * * Calling this method on a mutable Drawable will have no effect. * * @return This drawable. * @see ConstantState * @see #getConstantState() */public Drawable mutate() {    return this;}

翻译:让这个drawable可变,这个操作是不可逆的。一个可变Drawable可以保证不与其它的Drawable分享一个状态。当你需要修改资源中的Drawable的属性时这个方法是非常有用的,因为默认情况下加载相同资源的所有Drawable实例拥有同一个状态,如果你在一个地方改变了状态,其它的实例也会跟着改变。

0 0
原创粉丝点击