getBackground().setAlpha(0)设置透明度连下层控件背景色都被改变
2016-04-09 12:56
489 查看
从晚上9点就开始琢磨,为什么我在一个地方设置了getBackground().setAlpha(0);在别的activity中有些控件也变成透明的了,让我百思不得其解,哦,现在是晚上十一点四十五,问题终于解决(解决不了睡不着觉啊),觉得挺有意思的,分享一下,先举个例子:
?
两个textview,background都指向相同的资源,那如果text1.getBackground().setAlpha(255)(不透明),那text2的背景是不是也跟着变成不透明的呢,答案是yes,那为什么呢:默认情况下,所有的从同一资源(R.drawable.***等等)加载的实例都共享一个共用的状态,如果你更改一个实例的状态,其余的实例都会接收到相同的通知。
那怎么解决这种情况呢,看看这个方法:
?
翻译一下注释吧:让这个drawable可变,这个操作是不可逆的。一个可变Drawable可以保证不与其它的Drawable分享一个状态。当你需要修改资源中的Drawable的属性时这个方法是非常有用的,因为默认情况下加载相同资源的所有Drawable实例拥有同一个状态,如果你在一个地方改变了状态,其它的实例也会跟着改变。
OK。所以
?
就完美解决了。
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/text1" android:layout_width="match_parent" android:layout_height="60dp" android:background="@color/text_orange" /> <TextView android:id="@+id/text2" android:layout_width="match_parent" android:layout_height="60dp" android:background="@color/text_orange" /> </LinearLayout> |
那怎么解决这种情况呢,看看这个方法:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | /** * 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; } |
OK。所以
?
1 | text1.getBackground().mutate().setAlpha(255); |
相关文章推荐
- 第四次程序设计作业 C++计算器计算及命令行的使用 前缀表达式方法实现
- [fluentd学习]安装使用
- Couchbase:更好的Cache系统
- 257. Binary Tree Paths
- java中volatile关键字的含义
- hdu 5439 Ponds(长春网络赛——拓扑排序+搜索)
- POJ 3260 The Fewest Coins(完全背包+多重背包(转化为01背包))
- Syntax error, parameterized types are only available if source level is 1.5 or greater
- java用NLPIR对本地txt进行分词,并将分词结果写入本地
- centos6.5下使用yum安装mysql
- 迷茫中的自己
- 把读过的书记录下来。很多年以后再看看这个书单,应该很有趣~
- nodejs操作mongodb数据库封装DB类
- java项目、包、类
- Android Studio 2.0 稳定版
- Service之TelephonyManager使用
- lua编译环境搭建
- poj 1845 Sumdiv(求逆元)
- C语言之内存对齐
- 在线扫描PDF JPG 图片上面文字