2013-01-16 68 views
11

我需要創建一個簡單的Drawable具有所需顏色作爲背景顏色的對象,但我不知道如何在不使用XML模式的情況下以編程方式執行此操作(是否真的有可能?)。請告訴我,我需要它來做一個LayerDrawableSeekBar(改變背景編程SeekBar)。先謝謝你。如何以編程方式創建具有所需背景顏色的Drawable?

回答

29

您應該嘗試使用ColorDrawable。它可以用顏色構造器構造ColorDrawable(int color)

+0

謝謝。但是,請告訴我,我如何設置ID爲Drawable?我需要設置一個新的可繪製的「android:id/background」 – user1841247

+1

我不明白你想要做什麼。你需要什麼ID?您可以使用構造函數'LayerDrawable(Drawable [] layers)'將'ColorDrawable'添加到''LayerDrawable''。您不需要ColorDrawable的任何ID。層的id可以用'LayerDrawable.setId(int index,int id)' – Thrakbad

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); 
相關問題