Подтвердить что ты не робот

Как сделать кнопку подсветкой?

Я устанавливаю изображение как backgroud Button, но Button не выделяет выделение, когда его нажимают. Есть ли способ его решить.

4b9b3361

Ответ 1

Чтобы получить доступ к правильному ресурсу, вы найдете документацию StateList Drawable. Вы просто создаете и определяете его в своем подкаталоге res/drawable и устанавливаете его в качестве фона кнопок.

Ответ 2

Если это ImageButton, и вы не хотите использовать несколько доступных для каждого нажатого/не нажатого состояния, вы можете использовать фильтр цветных изображений. Это решение аналогично тому, которое используется Омаром.

Создайте OnTouchListener, изменяя цветной фильтр при касании.

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;
  }

}

Назначьте этому слушателю кнопку:

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

Обновление

Улучшен класс для применения маркера к ImageView, ImageButton или TextView через его составную Drawable.

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;
  }

}

Ответ 3

Смотрите здесь

А также здесь для Ромен Гай ответ:

В res/drawable создайте файл, называемый для примера mybutton_background.xml     и поместите что-то вроде этого внутри:

<?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> 

Затем установите это значение в качестве фона вашей кнопки с помощью   android:background="@drawable/mybutton_background"

Ответ 4

если вы используете

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

Тогда, как лучше объявить новый новый xml. с изображением вы можете указать изображение для каждого состояния события. как говорит Октавиан и вы можете установить этот xml в качестве фона

если ваш xml равен 'res/drawable/abc.xml', тогда установите фон как

android:background="@drawable/abc"

Вы также можете использовать ImageButton

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

Преимущество ImageButton заключается в том, что нет необходимости в другом изображении для выделения.

Ответ 5

Попробуйте сделать это, чтобы получить эффект плохого человека, не требуя создания нескольких копий ваших изображений. Установите значение альфа 0,8 на нужное значение:

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);

    }

}

Ответ 6

Я сделал это, переопределив класс 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);
}

}

в моей основной()

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

Ответ 7

Используйте View.setFocusableInTouchMode или android: focusableInTouchMode. В этом случае используйте эту часть для своей кнопки, либо в формате XML, либо в самом коде. Для получения дополнительной информации см. Http://developer.android.com/reference/android/view/View.html