Philipp
Philipp

Reputation: 11833

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

Upvotes: 0

Views: 4002

Answers (3)

chikka.anddev
chikka.anddev

Reputation: 9629

Your fault is you are not implementing click or touch event for your custom view. There is no click event for view. You can use touch event instead, so below code should work for you:

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 it will work for you.

Upvotes: 4

kscottz
kscottz

Reputation: 1082

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

Upvotes: 0

Prmths
Prmths

Reputation: 2032

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.

Upvotes: 1

Related Questions