国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android開發仿IOS滑動開關實現代碼

2019-10-23 18:29:24
字體:
來源:轉載
供稿:網友

Android開發仿IOS滑動開關實現代碼

Android與iOS相比,ios好多控件都是自帶的,而android需要使用自定義來實現。今天說的是ios的滑動開關,我層看到好多博客都是通過自定義ToggleButton實現的。這里我通過自定義view來實現他的效果。

首先在onsizechange里把2個半圓和一個矩形繪制出來。

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);    path.arcTo(rectF, 90, 180);    rectF.left = right - bottom;    rectF.right = right;    path.arcTo(rectF, 270, 180);    path.close();    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;

剩下的就是ondraw方法來繪制顏色,以及切換的效果。

protected void onDraw(Canvas canvas) {    super.onDraw(canvas);    paint.setStyle(Style.FILL);    paint.setAntiAlias(true);    canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));    if (isChoose) {      paint.setColor(onColor);    } else {      paint.setColor(offColor);    }    canvas.drawPath(path, paint);    isAnimation = isAnimation - 0.1f > 0 ? isAnimation - 0.1f : 0;    //縮放大小參數隨isAnimation變化而變化    final float scale = 0.98f * (isChoose ? isAnimation : 1 - isAnimation);    //保存canvas狀態    canvas.save();    canvas.scale(scale, scale, circle_cx, cy);    paint.setColor(offColor);    canvas.drawPath(path, paint);    canvas.restore();    paint.reset();    float bTranslateX = width - circle_width;    final float translate = bTranslateX * (isChoose ? 1 - isAnimation : isAnimation);    canvas.translate(translate, 0);    if (isAnimation > 0) {      invalidate();    }    canvas.save();    paint.setStyle(Style.FILL);    paint.setColor(offColor);    canvas.drawCircle(circle_width / 2, circle_width / 2, radius, paint); // 按鈕白底    paint.setStyle(Style.STROKE);    paint.setColor(borderColor);    paint.setStrokeWidth(borderwidth);    canvas.drawCircle(circle_width / 2, circle_width / 2, radius, paint); // 按鈕灰邊    canvas.restore();  }

最后我們在ontouch里面去改變他的狀態:

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

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 张家界市| 威宁| 梁山县| 贵德县| 福州市| 永善县| 乌恰县| 日土县| 桂平市| 淮南市| 大连市| 灵台县| 怀远县| 太白县| 澄迈县| 怀仁县| 芜湖市| 鸡西市| 雷波县| 攀枝花市| 南江县| 措勤县| 广元市| 广水市| 遂川县| 略阳县| 榕江县| 青阳县| 孟连| 江北区| 四子王旗| 萨迦县| 沾化县| 平山县| 民勤县| 垣曲县| 盘山县| 澎湖县| 曲麻莱县| 拉萨市| 新平|