SoFunction
Updated on 2025-03-02

Android development IOS sliding switch implementation code

Android development IOS sliding switch implementation code

Compared with iOS, many iOS controls are built-in, and Android needs to be implemented using customization. Today I am talking about the slide switch of iOS. I have seen many blogs on the layer that are implemented through custom ToggleButton. Here I use custom view to achieve its effect.

First draw 2 semicircles and a rectangle in onsizechange.

width = w;
    height = h;
    left = top = 0;
    right = width;
    bottom = height * 0.8f;
    cx = (right + left) / 2;
    cy = (bottom + top) / 2;
    RectF rectF = new RectF(left, top, bottom, bottom);
    (rectF, 90, 180);
     = right - bottom;
     = right;
    (rectF, 270, 180);
    ();
    circle_left = 0;
    circle_right = bottom;
    circle_width = circle_right - circle_left;
    float circle_height = (bottom - top) / 2;
    radius = circle_height * 0.9f;
    borderwidth = (int) (2 * (circle_height - radius));
    circle_cx = width - circle_height;

The rest is the ondraw method to draw colors and switch effects.

protected void onDraw(Canvas canvas) {
    (canvas);
    ();
    (true);
    (new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
    if (isChoose) {
      (onColor);
    } else {
      (offColor);
    }
    (path, paint);
    isAnimation = isAnimation - 0.1f > 0 ? isAnimation - 0.1f : 0;
    //The scaling size parameter changes with isAnimation    final float scale = 0.98f * (isChoose ? isAnimation : 1 - isAnimation);
    //Save canvas status    ();
    (scale, scale, circle_cx, cy);
    (offColor);
    (path, paint);
    ();
    ();
    float bTranslateX = width - circle_width;
    final float translate = bTranslateX * (isChoose ? 1 - isAnimation : isAnimation);
    (translate, 0);
    if (isAnimation > 0) {
      invalidate();
    }
    ();
    ();
    (offColor);
    (circle_width / 2, circle_width / 2, radius, paint); // Button on white    ();
    (borderColor);
    (borderwidth);
    (circle_width / 2, circle_width / 2, radius, paint); // button gray edge    ();
  }

Finally, we change his state in ontouch:

  public boolean onTouchEvent(MotionEvent event) {
    switch (()) {
      case MotionEvent.ACTION_DOWN:
        return true;
      case MotionEvent.ACTION_CANCEL:
        return true;
      case MotionEvent.ACTION_UP:
          isAnimation = 1;
          isChoose = !isChoose;
          (isChoose);
          invalidate();
        break;
    }
    return (event);

  }

Thank you for reading, I hope it can help you. Thank you for your support for this site!