Ask Your Question
3

How can I create a customized view that behaves like a button when clicked or touched?

asked 2021-09-23 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-09-11 02:00:00 +0000

djk gravatar image

To create a customized view that behaves like a button when clicked or touched, you can follow these steps:

  1. Extend the View class to create your custom view.

  2. Override the onTouchEvent method to detect when the view is clicked or touched.

  3. Set the Clickable property of your view to true to enable it to respond to touch events.

  4. Implement the performClick method to provide the default behavior of the view when clicked.

  5. Override the onDraw method to draw the custom view on the screen.

  6. Customize the appearance of the view to make it look like a button.

  7. Implement the behavior of the view when clicked, such as changing the background color or text.

Here's an example of a customized view that behaves like a button when clicked or touched:

public class MyButton extends View {

    private boolean mIsPressed;

    public MyButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        setClickable(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // Custom drawing code here
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch(event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mIsPressed = true;
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                mIsPressed = false;
                invalidate();
                performClick();
                break;
        }
        return true;
    }

    @Override
    public void performClick() {
        super.performClick();
        // Custom click behavior here
    }
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-09-23 11:00:00 +0000

Seen: 1 times

Last updated: Sep 11 '22