2014-10-22 5 views
5

Zuerst habe ich die grüne Farbe der Hintergrund der Ansicht Micon zu sein,wie die Farbe von GradientDrawable bekommen

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

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

Dann weiß ich nicht, wie die Farbe aus dieser Sicht des Hintergrund zu erhalten. .. es gibt keine getColor() Funktion ...

Antwort

4

die folgende Klasse funktioniert gut für mich bisher.

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

Dies kann nur in API erreicht werden 11+, wenn Ihr Hintergrund eine Farbe ist. Es ist einfach, dies als Drawable

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

zu bekommen Und wenn Sie auf Android 3.0+ sind Sie die Ressource-ID der Farbe bekommen kann.

int colorId = mIcon.getColor(); 

Und vergleichen Sie dies mit Ihren zugewiesenen Farben, dh.

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

Hoffe, das wird Ihnen helfen.

+0

wie Sie mContext.getResources(). GetDrawable (R.drawable sehen kann, wird hinzugefügt. roundbtn_white_normal); Dies gibt ein GradientDrawable zurück – shanwu

Verwandte Themen