2010-11-09 9 views
16

Configuré una imagen como fondo de botón, pero el botón no resalta al hacer clic en él. ¿Hay alguna manera de resolverlo?¿Cómo hacer resaltar el botón?

+1

Consulte esta [link] (http://stackoverflow.com/questions/4125774/android-button-set-onclick-background-image-change-with-xml/4125877#4125877) – David

Respuesta

10

Para llegar al recurso correcto aquí está la documentación del StateList Drawable. Simplemente cree y defina en su subdirectorio res/drawable y configúrelo como fondo de botones.

+0

¡Excelente respuesta! ¿Qué estás haciendo aquí en el pasado? ;-) –

13

Ver here

Y también here la respuesta de Romain Guy:

En res/dibujable, crear un archivo llamado por ejemplo mybutton_background.xml y poner algo como esto en el interior:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 

    <item android:state_focused="true" android:state_pressed="false" 
     android:drawable="@drawable/button_background_focus" /> 

    <item android:state_focused="true" android:state_pressed="true" 
     android:drawable="@drawable/button_background_pressed" /> 

    <item android:state_focused="false" android:state_pressed="true" 
     android:drawable="@drawable/button_background_pressed" /> 

    <item android:drawable="@drawable/button_background_normal" /> 

</selector> 

A continuación, establezca este dibujable como t El fondo de su botón con android:background="@drawable/mybutton_background"

+0

I puede' Llego a esos sitios web, porque estoy en China ... gracias. – Nick

+0

Puede usar un servidor Proxy para llegar allí. De todos modos, actualicé mi respuesta con la solución (la escrita por Romain Guy) –

4

si está utilizando

<Button 
    ------------------ 
android:background="@drawable/youimage" 
> 

A continuación, ya que es mejor declarar una nueva nueva XML. con la imagen puede especificar una imagen para cada event state. como dice Octavio
y se puede se puede establecer este XML como fondo

si su xml es 'res/estirable/abc.xml' a continuación, establecer como fondo

android:background="@drawable/abc" 

También puede utilizar ImageButton

<ImageButton 
---------------------- 
android:src="@drawable/youimage" 
/> 

El beneficio para ImageButton es que no necesita una imagen diferente para resaltar.

0

Uso View.setFocusableInTouchMode o androide: focusableInTouchMode. En este caso, use esta pieza para su Botón, ya sea en XML o en el código mismo. Para más detalles consulte : http: //developer.android.com/reference/android/view/View.html

+0

Soy China, aquí hay GFW, así que no puedo obtener http://developer.android.com/ gracias de todos modos – Nick

2

lo hice con cambio de clase Button

public class MButton extends Button { 
public MButton(Context context, AttributeSet attrs, int defStyle) { 
    super(context, attrs, defStyle); 
    // TODO Auto-generated constructor stub 
} 

public MButton(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    // TODO Auto-generated constructor stub 

} 

public MButton(Context context) { 
    super(context); 
    // TODO Auto-generated constructor stub 
} 

//define style 
public void setPressedBg(Integer[] mImageIds) { 
    StateListDrawable bg = new StateListDrawable(); 
    Drawable normal = this.getResources().getDrawable(mImageIds[0]); 
    Drawable selected = this.getResources().getDrawable(mImageIds[1]); 
    Drawable pressed = this.getResources().getDrawable(mImageIds[2]); 

    bg.addState(View.PRESSED_ENABLED_STATE_SET, pressed); 
    bg.addState(View.ENABLED_FOCUSED_STATE_SET, selected); 
    bg.addState(View.ENABLED_STATE_SET, normal); 
    bg.addState(View.FOCUSED_STATE_SET, selected); 
    bg.addState(View.EMPTY_STATE_SET, normal); 
    this.setBackgroundDrawable(bg); 
} 

//define style 
public void setPressedBg(Integer p1,Integer p2,Integer p3) { 
    StateListDrawable bg = new StateListDrawable(); 
    Drawable normal = this.getResources().getDrawable(p1); 
    Drawable selected = this.getResources().getDrawable(p2); 
    Drawable pressed = this.getResources().getDrawable(p3); 

    bg.addState(View.PRESSED_ENABLED_STATE_SET, pressed); 
    bg.addState(View.ENABLED_FOCUSED_STATE_SET, selected); 
    bg.addState(View.ENABLED_STATE_SET, normal); 
    bg.addState(View.FOCUSED_STATE_SET, selected); 
    bg.addState(View.EMPTY_STATE_SET, normal); 
    this.setBackgroundDrawable(bg); 
} 

}

en mi main()

toneButton.setPressedBg(R.drawable.button_tone_protrait_pipa, 
      R.drawable.button_tone_protrait_pipa1, 
      R.drawable.button_tone_protrait_pipa1); 
3

Pruebe esto para obtener el efecto de realce de un pobre sin la necesidad de hacer copias múltiples de sus imágenes. Establecer el valor de alfa 0,8 a un valor deseado:

import android.content.Context; 
import android.util.AttributeSet; 
import android.view.MotionEvent; 
import android.widget.ImageButton; 

public class EAImageButton extends ImageButton { 

    public EAImageButton(Context context) { 
     super(context); 
     // TODO Auto-generated constructor stub 

    } 
    public EAImageButton(Context context, AttributeSet attrs){ 
     super(context,attrs); 
    } 
    public EAImageButton(Context context, AttributeSet attrs, int defStyle){ 
     super(context,attrs,defStyle); 
    } 
    public void setImageResource (int resId){ 
     super.setImageResource(resId); 
    } 
    @Override 
    public boolean onTouchEvent(MotionEvent e){ 
     if(e.getAction() == MotionEvent.ACTION_DOWN){ 
      this.setAlpha((int)(0.8 * 255)); 
     }else if(e.getAction() == MotionEvent.ACTION_UP){ 
      this.setAlpha((int)(1.0 * 255)); 
     } 

     return super.onTouchEvent(e); 

    } 

} 
+0

+100 Clean and Smart. –

20

Si se trata de una ImageButton y no quieren utilizar varios estirable para cada estado presionado/sin prensar se podría utilizar el attibute filtro de color de las imágenes. Esta solución es similar a la utilizada por Omar.

Cree un OnTouchListener que modifique el filtro de color al tacto.

public class ButtonHighlighterOnTouchListener implements OnTouchListener { 

    final ImageButton imageButton; 

    public ButtonHighlighterOnTouchListener(final ImageButton imageButton) { 
    super(); 
    this.imageButton = imageButton; 
    } 

    public boolean onTouch(final View view, final MotionEvent motionEvent) { 
    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { 
     //grey color filter, you can change the color as you like 
     imageButton.setColorFilter(Color.argb(155, 185, 185, 185)); 
    } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) { 
     imageButton.setColorFilter(Color.argb(0, 185, 185, 185)); 
    } 
    return false; 
    } 

} 

asignar este oyente a su botón:

myButton = (ImageButton) findViewById(R.id.myButton); 
    myButton.setOnTouchListener(new ButtonHighlighterOnTouchListener(myButton)); 

actualización

mejora de la clase de aplicar marcador para ImageView, ImageButton o Vista de Texto a través de su Disponibles compuesto.

public class ButtonHighlighterOnTouchListener implements OnTouchListener { 

    private static final int TRANSPARENT_GREY = Color.argb(0, 185, 185, 185); 
    private static final int FILTERED_GREY = Color.argb(155, 185, 185, 185); 

    ImageView imageView; 
    TextView textView; 

    public ButtonHighlighterOnTouchListener(final ImageView imageView) { 
    super(); 
    this.imageView = imageView; 
    } 

    public ButtonHighlighterOnTouchListener(final TextView textView) { 
    super(); 
    this.textView = textView; 
    } 

    public boolean onTouch(final View view, final MotionEvent motionEvent) { 
    if (imageView != null) { 
     if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { 
     imageView.setColorFilter(FILTERED_GREY); 
     } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) { 
     imageView.setColorFilter(TRANSPARENT_GREY); // or null 
     } 
    } else { 
     for (final Drawable compoundDrawable : textView.getCompoundDrawables()) { 
     if (compoundDrawable != null) { 
      if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { 
      // we use PorterDuff.Mode. SRC_ATOP as our filter color is already transparent 
      // we should have use PorterDuff.Mode.LIGHTEN with a non transparent color 
      compoundDrawable.setColorFilter(FILTERED_GREY, PorterDuff.Mode.SRC_ATOP); 
      } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) { 
      compoundDrawable.setColorFilter(TRANSPARENT_GREY, PorterDuff.Mode.SRC_ATOP); // or null 
      } 
     } 
     } 
    } 
    return false; 
    } 

} 
+0

Solo una corrección: TIENE que volverse verdadero en onTouch() para decirle a SO que hizo alguna acción en la acción táctil. –

+0

esto es lo que estaba buscando ... imageView.setColorFilter() funciona perfecto –

Cuestiones relacionadas