0

I have created a custom View which I usually attach an onClickListener to. I'd like to have some button like behavior: if it is pressed, it should alter its appearance which is defined in the onDraw() method. However, this code does not work:

//In my custom View:

@Override
protected void onDraw(Canvas canvas)
{

    boolean pressed = isPressed();
    //draw depending on the value of pressed
}

//when creating the view:
MyView.setClickable(true);

pressed always has the value false. What's wrong?

Thanks a lot!

Philipp
  • 11,059
  • 8
  • 62
  • 115

3 Answers3

4

hey buddy,your fault is you are not implementing click or touch evnt for ur custom view.thr is no click evnt for view.you can use touch event instead of this:so below code work 4 u:


myView.setOnTouchListener(new OnTouchListener() {

public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub

    switch(event.getAction()){
    case MotionEvent.ACTION_DOWN:

    break;
    case MotionEvent.ACTION_UP:




    break;
    case MotionEvent.ACTION_MOVE:


    break;
    }

    return true;
}

});


in this code use action_up for click and you get it worked for you

chikka.anddev
  • 9,416
  • 7
  • 37
  • 45
1

have you considered just using a button to do what you want? you could use ToggleButton and write a short selector in xml that will allow you to specify an image to use when pressed or not. this question may be of some help to you.

Community
  • 1
  • 1
Prmths
  • 1,959
  • 4
  • 20
  • 38
0

To make your new custom button draw on clicks don't forget to invalidate the form as necessary. This is a little gotcha. E.g.

@Override
        public boolean onTouch(View v, MotionEvent event) 
        {
            /* Parse Event */ 
            this.invalidate();
            return true;
        }
kscottz
  • 1,062
  • 2
  • 13
  • 17