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?
Respuesta
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.
¡Excelente respuesta! ¿Qué estás haciendo aquí en el pasado? ;-) –
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"
I puede' Llego a esos sitios web, porque estoy en China ... gracias. – Nick
Puede usar un servidor Proxy para llegar allí. De todos modos, actualicé mi respuesta con la solución (la escrita por Romain Guy) –
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.
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
Soy China, aquí hay GFW, así que no puedo obtener http://developer.android.com/ gracias de todos modos – Nick
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);
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);
}
}
+100 Clean and Smart. –
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;
}
}
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. –
esto es lo que estaba buscando ... imageView.setColorFilter() funciona perfecto –
- 1. ¿Cómo puedo resaltar un botón con jQuery?
- 2. Android resaltar un botón imagen al hacer clic en
- 3. Cómo evitar el botón dentro de ListItem para resaltar
- 4. NSButton sin "resaltar el clic"
- 5. Jeditable - resaltar todo el texto después de hacer doble clic
- 6. Android cómo hacer resaltar la vista cuando se hace clic?
- 7. ¿Cómo resaltar el código fuente en HTML?
- 8. ¿Cómo puedo resaltar el texto en Scintilla?
- 9. ¿Cómo resaltar el elemento seleccionado en ListView?
- 10. Jquery: resaltar/resaltar la fila de la tabla al hacer clic
- 11. Cómo resaltar ListView-Items
- 12. ¿Cómo resaltar el elemento seleccionado en ItemsControl?
- 13. ¿Cómo hacer que el ancho del botón sea autofit el texto de un botón?
- 14. Android: ¿Cómo resaltar EditText programmatically?
- 15. ¿Cómo hacer que el botón no se pueda hacer clic después de hacer clic en él?
- 16. Lista personalizada No resaltar ListViewItem al hacer clic
- 17. ficha Resaltar en el menú
- 18. ¿Cómo hacer que el botón no sea transparente?
- 19. Cómo hacer clic y arrastrar el botón en Android
- 20. ¿Cómo simular un botón hacer clic usando el código?
- 21. Cómo hacer ingresar el botón de enviar en un formulario
- 22. Cómo asociar presionando "enter" con hacer clic en el botón?
- 23. Cómo hacer que el botón como hipervínculo en android
- 24. Detener IE al resaltar el primer botón de enviar en un formulario
- 25. Hacer emacs para resaltar la sintaxis postgresql de forma predeterminada
- 26. ¿Resaltar el soporte y el soporte Emacs?
- 27. C# Navegador web con hacer clic y resaltar
- 28. ¿Cómo puedo resaltar el código con el editor de ACE?
- 29. resaltar un elemento DOM al pasar el mouse, como inspeccionar
- 30. Cómo mostrar el botón UISplitViewcontroller en el botón
Consulte esta [link] (http://stackoverflow.com/questions/4125774/android-button-set-onclick-background-image-change-with-xml/4125877#4125877) – David