这里有新鲜出炉的精品教程,程序狗速度看过来!
Android 是一种基于 Linux 的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由 Google 公司和开放手机联盟领导及开发。尚未有统一中文名称,中国大陆地区较多人使用 "安卓" 或 "安致"。
这篇文章主要介绍了 Android getBackground().setAlpha 遇到问题解决办法的相关资料用,getBackground().setAlpha,导致其他布局背景透明度都改变的问题, 需要的朋友可以参考下
Android getBackground().setAlpha 遇到问题解决办法
前言:
使用 getBackground().setAlpha,导致其他布局背景透明度都改变的问题
从晚上 9 点就开始琢磨,为什么我在一个地方设置了 getBackground().setAlpha(0);在别的 activity 中有些控件也变成透明的了,让我百思不得其解,哦,现在是晚上十一点四十五,问题终于解决(解决不了睡不着觉啊),觉得挺有意思的,分享一下,先举个例子:
- <?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>
两个 textview,background 都指向相同的资源,那如果 text1.getBackground().setAlpha(255)(不透明),那 text2 的背景是不是也跟着变成不透明的呢,答案是 yes,那为什么呢:默认情况下,所有的从同一资源(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 实例拥有同一个状态,如果你在一个地方改变了状态,其它的实例也会跟着改变。
OK。所以
- text1.getBackground().mutate().setAlpha(255);
问题解决了!
来源: http://www.phperz.com/article/17/0429/332684.html