記得之前做的項(xiàng)目中遇到個奇怪的問題,頁面中設(shè)置了白色背景,但運(yùn)行起來的效果卻是灰色,并且每個手機(jī)的效果都不一樣,起初以為是適配的問題,最后幾經(jīng)波折終于確定了問題所在,是因?yàn)樵陧?xiàng)目中使用了view.getBackground().setAlpha(); 導(dǎo)致其他布局背景透明度都跟著改變 實(shí)際效果 自己寫了個demo測試下問題,以便分享
使用getBackground().setAlpha() 改變textview1的透明度 結(jié)果text2透明度也跟著改變,所以此方法會導(dǎo)致應(yīng)用內(nèi)其他頁面的 textview背景透明度跟著改變,
兩個textview,background都指向相同的資源,那如果text1.getBackground().setAlpha(255)(不透明),那text2的背景是不是也跟著變成不透明的呢,答案是yes,那為什么呢:默認(rèn)情況下,所有的從同一資源(R.drawable.*等等)加載的實(shí)例都共享一個共用的狀態(tài),如果你更改一個實(shí)例的狀態(tài),其余的實(shí)例都會接收到相同的通知。
那么該問題該如何解決呢?
/** * 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分享一個狀態(tài)。當(dāng)你需要修改資源中的Drawable的屬性時這個方法是非常有用的,因?yàn)槟J(rèn)情況下加載相同資源的所有Drawable實(shí)例擁有同一個狀態(tài),如果你在一個地方改變了狀態(tài),其它的實(shí)例也會跟著改變。 最后使用text1.getBackground().mutate().setAlpha(255);程序運(yùn)行正常 
改變text1的背景透明度,text2透明度不跟著改變。
新聞熱點(diǎn)
疑難解答