0

I want to highlight a button when pressed and release without using any images,so i am using the below code from one the post on SO but its not working for me:

public class MainActivity extends Activity {

    ImageButton myButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

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

    public class ButtonHighlighterOnTouchListener implements OnTouchListener {

    final ImageButton imageButton;

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

    @Override
    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.parseColor("#5F2444"));
        System.out.println("called down");
        } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
        imageButton.setColorFilter(Color.parseColor("#245F30"));
        System.out.println("called up");
        }
        return false;
    }

    }

What is the problem here?

Original post is here : How to make Button highlight?

Community
  • 1
  • 1
Goofy
  • 6,098
  • 17
  • 90
  • 156

2 Answers2

2

Ok i have solved it by myself hope it will help others too

public static void buttonEffect(View button) {
    button.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN: {
            v.getBackground().setColorFilter(0xe0f47521, PorterDuff.Mode.SRC_ATOP);
            v.invalidate();
            break;
        }
        case MotionEvent.ACTION_UP: {
            v.getBackground().clearColorFilter();
            v.invalidate();
            break;
        }
        }
        return false;
        }
    });
    }

You can change the color also , happy coding :)

Goofy
  • 6,098
  • 17
  • 90
  • 156
0

I suggest you to add this event in the switch, otherwise when the user clicks on the button and hold down until he go off the button, the button remains selected.

case MotionEvent.ACTION_CANCEL:
{
    v.getBackground().clearColorFilter();
    v.invalidate();
    break;
}

I hope I was helpful

Paolo
  • 555
  • 4
  • 28