2014-10-22 9 views
5

In primo luogo, ho impostato il colore verde come sfondo della vista micon,come ottenere il colore da GradientDrawable

View mIcon = findViewById(R.id.xxx); 

GradientDrawable gdraw = (GradientDrawable) mContext.getResources().getDrawable(R.drawable.roundbtn_white_normal); 
gdraw.setColor(Color.GREEN); 
mIcon.setBackgroundDrawable(gdraw); 

Poi, non so come ottenere il colore da sfondo di questa visione. .. non esiste la funzione getColor() ...

risposta

4

la classe seguente funziona bene per me finora.

import android.content.res.Resources; 
... 

// it's the same with the GradientDrawable, just make some proper modification to make it compilable 
public class ColorGradientDrawable extends Drawable { 
    ... 
    private int mColor; // this is the color which you try to get 
    ... 
    // original setColor function with little modification 
    public void setColor(int argb) { 
     mColor = argb; 
     mGradientState.setSolidColor(argb); 
     mFillPaint.setColor(argb); 
     invalidateSelf(); 
    } 

    // that's how I get the color from this drawable class 
    public int getColor() { 
     return mColor; 
    } 
    ... 

    // it's the same with GradientState, just make some proper modification to make it compilable 
    final public static class GradientState extends ConstantState { 
     ... 
    } 
} 
1

Questa operazione può essere eseguita solo in API 11+ se lo sfondo è un colore a tinta unita. E 'facile ottenere questo come un Drawable

Drawable mIconBackground = mIcon.getBackground();   
if (mIconBackground instanceof ColorDrawable) 
      color = ((ColorDrawable) background).getColor(); 

E se siete su Android 3.0+ è possibile ottenere l'ID risorsa del colore.

int colorId = mIcon.getColor(); 

E confrontare questo ai colori assegnati, vale a dire.

if (colorId == Color.GREEN) { 
    log("color is green"); 
} 

Spero che questo ti possa aiutare.

+0

come si può vedere mContext.getResources(). GetDrawable (R.drawable. roundbtn_white_normal); questo restituisce GradientDrawable – shanwu

Problemi correlati