2011-07-15 9 views
5

Quiero cambiar el valor alfa de un dibujo cuando se presiona. Por lo tanto, creo dos elementos dibujables y los coloco en un StateListDrawable y establezco el valor alfa para el estado presionado. Pero simplemente no funciona.¿Cómo establecer el valor alfa para dibujable en un StateListDrawable?

StateListDrawable content = new StateListDrawable(); 
Drawable contentSelected = this.getResources().getDrawable(
R.drawable.content_background); 
contentSelected.mutate().setAlpha(100); 

Drawable contentNormal = this.getResources().getDrawable(R.drawable.content_background); 

content.addState(new int[] { android.R.attr.state_pressed }, contentSelected); 
content.addState(new int[] { android.R.attr.state_enabled }, contentNormal); 

ImageButton button = (ImageButton) view.findViewById(R.id.content_thumbnail); 
button.setImageDrawable(content); 

actualización: Mi solución final es crear una subclase de BitmapDrawable como este, y cambiar el valor de alfa en el método onStateChange().

public AlphaAnimatedDrawable(Resources res, Bitmap bitmap) { 
    super(res, bitmap); 
    this.setState(new int[] { android.R.attr.state_pressed, android.R.attr.state_selected, 
      android.R.attr.state_enabled }); 
} 

private static final int PRESSED_ALPHA = 180; 
private static final int REGULAR_ALPHA = 255; 

@Override 
protected boolean onStateChange(int[] states) { 

    for (int state : states) { 
     if (state == android.R.attr.state_pressed) { 
      setAlpha(PRESSED_ALPHA); 
     } else if (state == android.R.attr.state_selected) { 
      setAlpha(REGULAR_ALPHA); 
     } else if (state == android.R.attr.state_enabled) { 
      setAlpha(REGULAR_ALPHA); 
     } 
    } 
    return true; 
} 
+0

Arg, me acaba de golpear el mismo problema! ¡Trataré de avisarte si lo soluciono! –

+0

me ayudó. Si extiende Drawable, también necesita @Override public boolean isStateful() { return true; } –

Respuesta

6

Esto funcionó para mí

StateListDrawable drawable = new StateListDrawable(); 

    Bitmap enabledBitmap = ((BitmapDrawable)mIcon).getBitmap(); 

    // Setting alpha directly just didn't work, so we draw a new bitmap! 
    Bitmap disabledBitmap = Bitmap.createBitmap(
     mIcon.getIntrinsicWidth(), 
     mIcon.getIntrinsicHeight(), Config.ARGB_8888); 
    Canvas canvas = new Canvas(disabledBitmap); 

    Paint paint = new Paint(); 
    paint.setAlpha(126); 
    canvas.drawBitmap(enabledBitmap, 0, 0, paint); 

    BitmapDrawable disabled = new BitmapDrawable(mContext.getResources(), disabledBitmap); 

    drawable.addState(new int[] { -android.R.attr.state_enabled}, disabled); 
    drawable.addState(StateSet.WILD_CARD, mIcon); 
+0

Esto funciona pero tenga cuidado, crear mapas de bits siempre es una gran abolladura en su memoria –

Cuestiones relacionadas