2013-01-16 15 views

risposta

29

Si dovrebbe provare a utilizzare un ColorDrawable. Può essere costruito con un colore usando il costruttore ColorDrawable(int color)

+0

Grazie . Ma per favore, dimmi, come posso impostare Id per Drawable? Devo impostare "android: id/background" per un nuovo drawable – user1841247

+1

Non capisco cosa stai cercando di fare. Per cosa ti serve l'id? Puoi semplicemente aggiungere 'ColorDrawable' al tuo' LayerDrawable' usando il costruttore 'LayerDrawable (Drawable [] layers)'. Non hai bisogno di alcun ID per ColorDrawable. L'id del livello può quindi essere impostato con 'LayerDrawable.setId (int index, int id)' – Thrakbad

5

ColorDrawable ti sarà utile nel tuo caso, puoi passare il parametro color per il tuo drawable.

o si può fare qualcosa di simile di seguito:

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); 

sopra il codice è originariamente pubblicato here

+0

Grazie. Ma per favore, dimmi, come posso impostare Id per Drawable? Devo impostare "android: id/background" per un nuovo drawable – user1841247

+0

in questo modo non è possibile in fase di esecuzione, è meglio creare la funzione passare l'id della vista e impostare il colore appropriato per la visualizzazione. – RobinHood

3

Come è suggerito da @Thrakbad, è possibile utilizzare ColorDrawable:

TextView textView = new TextView(this); 
    ColorDrawable colorDrawable = new ColorDrawable(0xFFFF0000); 
    textView.setBackgroundDrawable(colorDrawable); 
Problemi correlati