記得之前做的項目中遇到個奇怪的問題,頁面中設置了白色背景,但運行起來的效果卻是灰色,并且每個手機的效果都不一樣,起初以為是適配的問題,最后幾經波折終于確定了問題所在,是因為在項目中使用了view.getBackground().setAlpha(); 導致其他布局背景透明度都跟著改變 實際效果 自己寫了個demo測試下問題,以便分享 使用getBackground().setAlpha() 改變textview1的透明度 結果text2透明度也跟著改變,所以此方法會導致應用內其他頁面的 textview背景透明度跟著改變,
兩個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實例擁有同一個狀態,如果你在一個地方改變了狀態,其它的實例也會跟著改變。 最后使用text1.getBackground().mutate().setAlpha(255);程序運行正常
改變text1的背景透明度,text2透明度不跟著改變。
新聞熱點
疑難解答