Custom view with button like behavior on click/touch
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
prot开发者_运维问答ected 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!
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
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.
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;
}
精彩评论