Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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