[問題] Drawable mutate 使用方式

看板AndroidDev作者 (小黑)時間9年前 (2016/04/14 17:35), 編輯推噓0(009)
留言9則, 2人參與, 最新討論串1/1
大家好 這次在練習使用drawable的layer-list 碰到一些問題,上來求助大家 我用xml寫了一個 箭頭的圖案(arrow_shape.xml) 並且想用程式碼動態更改顏色 但是因為一個Drawable檔案載入至記憶體之後 為了方便重複使用以及節省資源 所以在記憶體內的Drawable物件有一個static的變數 去儲存它的顏色值 而我會在螢幕上呈現出很多個箭頭 箭頭的顏色是隨機選擇的,而箭頭旁邊會有文字告知正確顏色是什麼 碰到問題是箭頭的顏色不一定會正確 思考之後發現應該是CPU平行處理的關係 一般來說正常的處理方式是這樣 更改顏色→顯示在螢幕上 但假設我今天要呈現一個紅色箭頭(A)跟一個黃色箭頭(B) cpu可能這樣跑 A箭頭改成紅色→B箭頭改成黃色→顯示A在螢幕上→顯示B在螢幕上 結果因為static的顏色值的關係,導致A B都是黃色 請問應該怎麼解決才好呢!??? 我有查到可以使用mutate()這個method去處理 但是自己嘗試使用的結果會導致全部顏色都是第一次隨機決定的顏色 請問有人有解法嗎... 謝謝各位 以下附上箭頭檔案以及更改顏色的原始碼 arrow_shape.xml <?xml version="1.0" encoding="UTF-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/arrow"> <shape android:shape="rectangle"> <size android:width="55dp" android:height="59dp" /> <solid android:color="#5EB888" /> <corners android:radius="0dp"/> </shape> </item> <item android:top="55dp" android:bottom="-30dp" android:left="-22dp"> <!--左邊的三角形--> <rotate android:fromDegrees="42"> <shape android:shape="rectangle"> <solid android:color="#ffffff" /> </shape> </rotate> </item> <item android:top="55dp" android:bottom="-30dp" android:right="-22dp"> <!--右邊的三角形--> <rotate android:fromDegrees="-42"> <shape android:shape="rectangle"> <solid android:color="#ffffff" /> </shape> </rotate> </item> </layer-list> 動態換顏色的程式碼 LayerDrawable d = (LayerDrawable) ContextCompat.getDrawable(getContext(), R.drawable.arrow_shape); GradientDrawable shape = (GradientDrawable)d.findDrawableByLayerId(R.id.arrow); shape.setColor(getResources().getColor(colorRef)); this.setBackgroundResource(backgroundImage); 在這邊我的this是relativelayout 謝謝各位~~ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.121.196.88 ※ 文章網址: https://www.ptt.cc/bbs/AndroidDev/M.1460626532.A.220.html

04/18 17:20, , 1F
我不懂明明是不同的Drawable(不同顏色)為什麼硬要用同一個
04/18 17:20, 1F

04/18 17:25, , 2F
就算你弄到可以設顏色>系統draw>換顏色>系統draw,第一次沒
04/18 17:25, 2F

04/18 17:26, , 3F
問題,那後面你能控制什麼時候view會重畫嗎? 每次重畫前都
04/18 17:26, 3F

04/18 17:26, , 4F
依現在是要給哪個view用再去改顏色?
04/18 17:26, 4F

04/18 17:33, , 5F
Drawable不是只有設給view用完後就能隨便改,是有狀態的
04/18 17:33, 5F

04/18 17:35, , 6F
應該每個顏色的都要從 getDrawable > mutate > 設顏色
04/18 17:35, 6F

04/18 17:35, , 7F
不要共用不同顏色的
04/18 17:35, 7F

04/19 00:51, , 8F
謝謝S大 我本來的想法是模組化 想說同一張圖 可以使
04/19 00:51, 8F

04/19 00:52, , 9F
用程式去更改顏色就好 我懂他的狀態的意思了 謝謝
04/19 00:52, 9F
文章代碼(AID): #1N3sHa8W (AndroidDev)