我需要創建一個簡單的Drawable
具有所需顏色作爲背景顏色的對象,但我不知道如何在不使用XML模式的情況下以編程方式執行此操作(是否真的有可能?)。請告訴我,我需要它來做一個LayerDrawable
和SeekBar
(改變背景編程SeekBar
)。先謝謝你。如何以編程方式創建具有所需背景顏色的Drawable?
11
A
回答
29
您應該嘗試使用ColorDrawable。它可以用顏色構造器構造ColorDrawable(int color)
5
ColorDrawable會對你有所幫助,你可以爲你的drawable傳遞參數color。
,或者你可以做一些象下面這樣:因爲它是由@Thrakbad建議
ImageView imgStatus = (ImageView) findViewById(R.id.imgInfoIcon);
// Load the icon as drawable object
Drawable d = getResources().getDrawable(R.drawable.ic_menu_info_details);
// Get the color of the icon depending on system state
int iconColor = android.graphics.Color.BLACK
if (systemState == Status.ERROR)
iconColor = android.graphics.Color.RED
else if (systemState == Status.WARNING)
iconColor = android.graphics.Color.YELLOW
else if (systemState == Status.OK)
iconColor = android.graphics.Color.GREEN
// Set the correct new color
d.setColorFilter(iconColor, Mode.MULTIPLY);
// Load the updated drawable to the image viewer
imgStatus.setImageDrawable(d);
上面的代碼最初張貼here
+0
設置謝謝。但是,請告訴我,我如何設置ID爲Drawable?我需要設置「android:id/background」爲一個新的可繪製的 – user1841247
+0
這樣你不能在運行時,它更好地創建函數傳遞你的視圖id,併爲你的視圖設置適當的顏色。 – RobinHood
3
,您可以使用ColorDrawable
:
TextView textView = new TextView(this);
ColorDrawable colorDrawable = new ColorDrawable(0xFFFF0000);
textView.setBackgroundDrawable(colorDrawable);
相關問題
- 1. 如何以編程方式獲取工具欄背景顏色?
- 2. 如何以編程方式設置UINavigationbar的背景顏色?
- 3. 如何以編程方式更改按鈕的背景顏色
- 4. 如何以編程方式設置UILabel的背景顏色?
- 5. 如何以編程方式設置tablelayout行背景顏色
- 6. 如何以編程方式改變背景顏色,而從iPhone
- 7. 如何以編程方式更改對話框背景顏色?
- 8. 更改以編程方式創建的單選按鈕的背景顏色
- 9. 如何以編程方式將活動的背景顏色設置爲白色?
- 10. 以編程方式設置形狀的背景顏色
- 11. Swift:以編程方式更改窗口的背景顏色
- 12. 以編程方式設置listview的背景顏色
- 13. 以編程方式更改ActionBarSherlock的背景顏色
- 14. 以編程方式更改某些文本的背景顏色
- 15. 以編程方式更改背景顏色的視圖
- 16. 以編程方式更改ListView行的背景顏色(wpf)
- 17. 以編程方式更改所需的背景模式
- 18. 如何以編程方式設置WatchKit應用程序的背景顏色?
- 19. 以編程方式設置drawable的背景圖像
- 20. 創建具有不同背景顏色的線條列表的最佳方式
- 21. 如何以編程方式更改Drawable的顏色而不着色Alpha像素
- 22. 如何以編程方式爲LinearLayout創建背景
- 23. 如何以編程方式創建20x20px單元網格背景?
- 24. Silverlight:以編程方式設置組合框背景顏色
- 25. oracle窗體以編程方式更改窗口背景顏色?
- 26. 以編程方式更改列表框項目背景顏色
- 27. 以編程方式更改翻轉開關背景顏色
- 28. XNA以編程方式更改背景顏色
- 29. 以編程方式獲取UIKeyboard背景顏色
- 30. 以編程方式刪除UIButton背景顏色
謝謝。但是,請告訴我,我如何設置ID爲Drawable?我需要設置一個新的可繪製的「android:id/background」 – user1841247
我不明白你想要做什麼。你需要什麼ID?您可以使用構造函數'LayerDrawable(Drawable [] layers)'將'ColorDrawable'添加到''LayerDrawable''。您不需要ColorDrawable的任何ID。層的id可以用'LayerDrawable.setId(int index,int id)' – Thrakbad