Implementing a Custom Two-Way Switch with Ripple Animation in Android
This article explains how to create a custom Android view that functions as a two‑way vertical switch with top‑bottom activation, indicator dots, ripple effects, dynamic text and color changes, and provides the full implementation steps from drawing to touch handling and external control.
After Android 4.0 introduced the standard Switch widget, a vertical two‑way switch was not available, so the author implemented a custom view to achieve this functionality and documented the approach.
Step 1: Draw the button and indicator dots – In the onDraw method the button background, state‑indicating circles, and text are rendered. Bitmaps are created with Bitmap.createBitmap() , circles are drawn using canvas.drawCircle() , and text size and color are adjusted according to the current position.
Step 2: Implement vertical sliding and state detection – The view overrides onTouchEvent to capture Y‑axis movement via MotionEvent . While the finger moves, the view calls invalidate() to trigger redraws. When the finger lifts, the distance determines whether the switch is at the top (on), bottom (on), or middle (off) and a flag mIsSliding controls automatic snapping.
Step 3: Add ripple animation – Ripple effects are built with AnimatorSet and ValueAnimator . The animator runs from 0 to 1 over 2000 ms, updating the ripple radius and opacity in an addUpdateListener . The paint’s alpha must be set after setColor() because the color method includes its own alpha.
Step 4: Expose control methods – A public method allows external code to set the switch state programmatically, updating the view accordingly.
The implementation covers drawing, touch handling, automatic positioning, ripple animation, and an external API, providing a complete solution for a vertical two‑way switch in Android.
Author: Ma Yonglong, Android developer at Yiche since 2016.
Yiche Technology
Official account of Yiche Technology, regularly sharing the team's technical practices and insights.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.