这里有新鲜出炉的精品教程,程序狗速度看过来!
Android 是一种基于 Linux 的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由 Google 公司和开放手机联盟领导及开发。尚未有统一中文名称,中国大陆地区较多人使用 "安卓" 或 "安致"。
这篇文章主要介绍了 android 开发仿 IOS 滑动开关实现代码的相关资料, 需要的朋友可以参考下
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);
- }
来源: http://www.phperz.com/article/17/0822/337694.html