11.粘性控件

粘性控件 (对View的自定义)
应用场景: 未读提醒的清除
功能实现:
> 1. 画静态图 OK
> 2. 把静态的数值变成变量(计算得到真实的变量) OK 
> 3. 不断地修改变量, 重绘界面, 动起来了.
> 4. 功能分析:
    a. 拖拽超出范围,断开, 松手, 消失
    b. 拖拽超出范围,断开,放回去了,恢复
    c. 拖拽没超出范围, 松手,弹回去
240px-Bezier_2_big.gif240px-Bezier_3_big.gif

没有布局:
MainActivity
  1. public class MainActivity extends Activity {
  2. @Override
  3. protected void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. requestWindowFeature(Window.FEATURE_NO_TITLE);
  6. setContentView(new GooView(MainActivity.this));
  7. }
  8. }
Utils
  1. public class Utils {
  2. public static Toast mToast;
  3. public static void showToast(Context mContext, String msg) {
  4. if (mToast == null) {
  5. mToast = Toast.makeText(mContext, "", Toast.LENGTH_SHORT);
  6. }
  7. mToast.setText(msg);
  8. mToast.show();
  9. }
  10. /**
  11. * dip 转换成 px
  12. * @param dip
  13. * @param context
  14. * @return
  15. */
  16. public static float dip2Dimension(float dip, Context context) {
  17. DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
  18. return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, displayMetrics);
  19. }
  20. /**
  21. * @param dip
  22. * @param context
  23. * @param complexUnit {@link TypedValue#COMPLEX_UNIT_DIP} {@link TypedValue#COMPLEX_UNIT_SP}}
  24. * @return
  25. */
  26. public static float toDimension(float dip, Context context, int complexUnit) {
  27. DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
  28. return TypedValue.applyDimension(complexUnit, dip, displayMetrics);
  29. }
  30. /** 获取状态栏高度
  31. * @param v
  32. * @return
  33. */
  34. public static int getStatusBarHeight(View v) {
  35. if (v == null) {
  36. return 0;
  37. }
  38. Rect frame = new Rect();
  39. v.getWindowVisibleDisplayFrame(frame);
  40. return frame.top;
  41. }
  42. public static String getActionName(MotionEvent event) {
  43. String action = "unknow";
  44. switch (MotionEventCompat.getActionMasked(event)) {
  45. case MotionEvent.ACTION_DOWN:
  46. action = "ACTION_DOWN";
  47. break;
  48. case MotionEvent.ACTION_MOVE:
  49. action = "ACTION_MOVE";
  50. break;
  51. case MotionEvent.ACTION_UP:
  52. action = "ACTION_UP";
  53. break;
  54. case MotionEvent.ACTION_CANCEL:
  55. action = "ACTION_CANCEL";
  56. break;
  57. case MotionEvent.ACTION_SCROLL:
  58. action = "ACTION_SCROLL";
  59. break;
  60. case MotionEvent.ACTION_OUTSIDE:
  61. action = "ACTION_SCROLL";
  62. break;
  63. default:
  64. break;
  65. }
  66. return action;
  67. }
  68. }
GooView
  1. /**
  2. * 粘性控件
  3. * @author poplar
  4. *
  5. */
  6. public class GooView extends View {
  7. private static final String TAG = "TAG";
  8. private Paint mPaint;
  9. public GooView(Context context) {
  10. this(context, null);
  11. }
  12. public GooView(Context context, AttributeSet attrs) {
  13. this(context, attrs , 0);
  14. }
  15. public GooView(Context context, AttributeSet attrs, int defStyle) {
  16. super(context, attrs, defStyle);
  17. // 做初始化操作
  18. mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
  19. mPaint.setColor(Color.RED);
  20. }
  21. PointF[] mStickPoints = new PointF[]{
  22. new PointF(250f, 250f),
  23. new PointF(250f, 350f)
  24. };
  25. PointF[] mDragPoints = new PointF[]{
  26. new PointF(50f, 250f),
  27. new PointF(50f, 350f)
  28. };
  29. PointF mControlPoint = new PointF(150f, 300f);
  30. PointF mDragCenter = new PointF(80f, 80f);
  31. float mDragRadius = 14f;
  32. PointF mStickCenter = new PointF(150f, 150f);
  33. float mStickRadius = 12f;
  34. private int statusBarHeight;
  35. float farestDistance = 80f;
  36. private boolean isOutofRange;
  37. private boolean isDisappear;
  38. @Override
  39. protected void onDraw(Canvas canvas) {
  40. // 计算连接点值, 控制点, 固定圆半径
  41. // 1. 获取固定圆半径(根据两圆圆心距离)
  42. float tempStickRadius = getTempStickRadius();
  43. // 2. 获取直线与圆的交点
  44. float yOffset = mStickCenter.y - mDragCenter.y;
  45. float xOffset = mStickCenter.x - mDragCenter.x;
  46. Double lineK = null;
  47. if(xOffset != 0){
  48. lineK = (double) (yOffset / xOffset);
  49. }
  50. // 通过几何图形工具获取交点坐标
  51. mDragPoints = GeometryUtil.getIntersectionPoints(mDragCenter, mDragRadius, lineK);
  52. mStickPoints = GeometryUtil.getIntersectionPoints(mStickCenter, tempStickRadius, lineK);
  53. // 3. 获取控制点坐标
  54. mControlPoint = GeometryUtil.getMiddlePoint(mDragCenter, mStickCenter);
  55. // 保存画布状态
  56. canvas.save();
  57. canvas.translate(0, -statusBarHeight);
  58. // 画出最大范围(参考用)
  59. mPaint.setStyle(Style.STROKE);
  60. canvas.drawCircle(mStickCenter.x, mStickCenter.y, farestDistance, mPaint);
  61. mPaint.setStyle(Style.FILL);
  62. if(!isDisappear){
  63. if(!isOutofRange){
  64. // 3. 画连接部分
  65. Path path = new Path();
  66. // 跳到点1
  67. path.moveTo(mStickPoints[0].x, mStickPoints[0].y);
  68. // 画曲线1 -> 2
  69. path.quadTo(mControlPoint.x, mControlPoint.y, mDragPoints[0].x, mDragPoints[0].y);
  70. // 画直线2 -> 3
  71. path.lineTo(mDragPoints[1].x, mDragPoints[1].y);
  72. // 画曲线3 -> 4
  73. path.quadTo(mControlPoint.x, mControlPoint.y, mStickPoints[1].x, mStickPoints[1].y);
  74. path.close();
  75. canvas.drawPath(path, mPaint);
  76. // 画附着点(参考用)
  77. mPaint.setColor(Color.BLUE);
  78. canvas.drawCircle(mDragPoints[0].x, mDragPoints[0].y, 3f, mPaint);
  79. canvas.drawCircle(mDragPoints[1].x, mDragPoints[1].y, 3f, mPaint);
  80. canvas.drawCircle(mStickPoints[0].x, mStickPoints[0].y, 3f, mPaint);
  81. canvas.drawCircle(mStickPoints[1].x, mStickPoints[1].y, 3f, mPaint);
  82. mPaint.setColor(Color.RED);
  83. // 2. 画固定圆
  84. canvas.drawCircle(mStickCenter.x, mStickCenter.y, tempStickRadius, mPaint);
  85. }
  86. // 1. 画拖拽圆
  87. canvas.drawCircle(mDragCenter.x, mDragCenter.y, mDragRadius, mPaint);
  88. }
  89. // 恢复上次的保存状态
  90. canvas.restore();
  91. }
  92. // 获取固定圆半径(根据两圆圆心距离)
  93. private float getTempStickRadius() {
  94. float distance = GeometryUtil.getDistanceBetween2Points(mDragCenter, mStickCenter);
  95. // if(distance> farestDistance){
  96. // distance = farestDistance;
  97. // }
  98. distance = Math.min(distance, farestDistance);
  99. // 0.0f -> 1.0f
  100. float percent = distance / farestDistance;
  101. Log.d(TAG, "percent: " + percent);
  102. // percent , 100% -> 20%
  103. return evaluate(percent, mStickRadius, mStickRadius * 0.2f);
  104. }
  105. public Float evaluate(float fraction, Number startValue, Number endValue) {
  106. float startFloat = startValue.floatValue();
  107. return startFloat + fraction * (endValue.floatValue() - startFloat);
  108. }
  109. @Override
  110. public boolean onTouchEvent(MotionEvent event) {
  111. float x;
  112. float y;
  113. switch (event.getAction()) {
  114. case MotionEvent.ACTION_DOWN:
  115. isOutofRange = false;
  116. isDisappear = false;
  117. x = event.getRawX();
  118. y = event.getRawY();
  119. updateDragCenter(x, y);
  120. break;
  121. case MotionEvent.ACTION_MOVE:
  122. x = event.getRawX();
  123. y = event.getRawY();
  124. updateDragCenter(x, y);
  125. // 处理断开事件
  126. float distance = GeometryUtil.getDistanceBetween2Points(mDragCenter, mStickCenter);
  127. if(distance > farestDistance){
  128. isOutofRange = true;
  129. invalidate();
  130. }
  131. break;
  132. case MotionEvent.ACTION_UP:
  133. if(isOutofRange){
  134. float d = GeometryUtil.getDistanceBetween2Points(mDragCenter, mStickCenter);
  135. if(d > farestDistance){
  136. // a. 拖拽超出范围,断开, 松手, 消失
  137. isDisappear = true;
  138. invalidate();
  139. }else {
  140. //b. 拖拽超出范围,断开,放回去了,恢复
  141. updateDragCenter(mStickCenter.x, mStickCenter.y);
  142. }
  143. }else {
  144. // c. 拖拽没超出范围, 松手,弹回去
  145. final PointF tempDragCenter = new PointF(mDragCenter.x, mDragCenter.y);
  146. ValueAnimator mAnim = ValueAnimator.ofFloat(1.0f);
  147. mAnim.addUpdateListener(new AnimatorUpdateListener() {
  148. @Override
  149. public void onAnimationUpdate(ValueAnimator mAnim) {
  150. // 0.0 -> 1.0f
  151. float percent = mAnim.getAnimatedFraction();
  152. PointF p = GeometryUtil.getPointByPercent(tempDragCenter, mStickCenter, percent);
  153. updateDragCenter(p.x, p.y);
  154. }
  155. });
  156. mAnim.setInterpolator(new OvershootInterpolator(4));
  157. mAnim.setDuration(500);
  158. mAnim.start();
  159. }
  160. break;
  161. default:
  162. break;
  163. }
  164. return true;
  165. }
  166. /**
  167. * 更新拖拽圆圆心坐标,并重绘界面
  168. * @param x
  169. * @param y
  170. */
  171. private void updateDragCenter(float x, float y) {
  172. mDragCenter.set(x, y);
  173. invalidate();
  174. }
  175. @Override
  176. protected void onSizeChanged(int w, int h, int oldw, int oldh) {
  177. super.onSizeChanged(w, h, oldw, oldh);
  178. statusBarHeight = Utils.getStatusBarHeight(this);
  179. }
  180. }
GeometryUtil
  1. /**
  2. * 几何图形工具
  3. */
  4. public class GeometryUtil {
  5. /**
  6. * As meaning of method name.
  7. * 获得两点之间的距离
  8. * @param p0
  9. * @param p1
  10. * @return
  11. */
  12. public static float getDistanceBetween2Points(PointF p0, PointF p1) {
  13. float distance = (float) Math.sqrt(Math.pow(p0.y - p1.y, 2) + Math.pow(p0.x - p1.x, 2));
  14. return distance;
  15. }
  16. /**
  17. * Get middle point between p1 and p2.
  18. * 获得两点连线的中点
  19. * @param p1
  20. * @param p2
  21. * @return
  22. */
  23. public static PointF getMiddlePoint(PointF p1, PointF p2) {
  24. return new PointF((p1.x + p2.x) / 2.0f, (p1.y + p2.y) / 2.0f);
  25. }
  26. /**
  27. * Get point between p1 and p2 by percent.
  28. * 根据百分比获取两点之间的某个点坐标
  29. * @param p1
  30. * @param p2
  31. * @param percent
  32. * @return
  33. */
  34. public static PointF getPointByPercent(PointF p1, PointF p2, float percent) {
  35. return new PointF(evaluateValue(percent, p1.x , p2.x), evaluateValue(percent, p1.y , p2.y));
  36. }
  37. /**
  38. * 根据分度值,计算从start到end中,fraction位置的值。fraction范围为0 -> 1
  39. * @param fraction
  40. * @param start
  41. * @param end
  42. * @return
  43. */
  44. public static float evaluateValue(float fraction, Number start, Number end){
  45. return start.floatValue() + (end.floatValue() - start.floatValue()) * fraction;
  46. }
  47. /**
  48. * Get the point of intersection between circle and line.
  49. * 获取 通过指定圆心,斜率为lineK的直线与圆的交点。
  50. *
  51. * @param pMiddle The circle center point.
  52. * @param radius The circle radius.
  53. * @param lineK The slope of line which cross the pMiddle.
  54. * @return
  55. */
  56. public static PointF[] getIntersectionPoints(PointF pMiddle, float radius, Double lineK) {
  57. PointF[] points = new PointF[2];
  58. float radian, xOffset = 0, yOffset = 0;
  59. if(lineK != null){
  60. radian= (float) Math.atan(lineK);
  61. xOffset = (float) (Math.sin(radian) * radius);
  62. yOffset = (float) (Math.cos(radian) * radius);
  63. }else {
  64. xOffset = radius;
  65. yOffset = 0;
  66. }
  67. points[0] = new PointF(pMiddle.x + xOffset, pMiddle.y - yOffset);
  68. points[1] = new PointF(pMiddle.x - xOffset, pMiddle.y + yOffset);
  69. return points;
  70. }
  71. }



来自为知笔记(Wiz)


附件列表

 

转载于:https://www.cnblogs.com/sixrain/p/5041965.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/419205.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

前端学习(1704):前端系列javascript之问题解答2和总结

//闭包隐藏数据 function createCache() {const data {} //闭包中的数据 被访问 不被外界访问return {set: function(key, val) {data[key] val},get: function(key) {return data[key];}} } const c createCache(); c.set(a, 100); console.log(c.get(a)); 弹出1,2,3&…

POST请求传入中文参数,接收端乱码

问题描述&#xff1a;通过post请求调试短信接口发送出去后&#xff0c;客户端无法收到短信&#xff0c;中文内容乱码 追踪过程&#xff1a; 接口采用post请求进行&#xff0c;无法收取短信的接口代码如下&#xff1a; public static String sendPost(String url, Map<Stri…

TCP/IP协议模型

1. 数据链路层 作用(1) 实现网卡接口的网络驱动&#xff0c;以处理数据在以太网线等物理媒介上的传输   (2) 网络驱动程序隐藏了不同物理网络的不同电气特性&#xff0c;为上层协议提供一个统一的接口 应用ARP和RARP(Reverse Address Resolve Protocol)即逆地址解析协议&am…

【转】 Pro Android学习笔记(二九):用户界面和控制(17):include和merge

目录(?)[-] xml控件代码重用includexml控件代码重用merge横屏和竖屏landsacpe portraitxml控件代码重用&#xff1a;include 如果我们定义一个控件&#xff0c;需要在不同的layout中重复使用&#xff0c;或者在同一个layout中重复使用&#xff0c;可以采用include的方式。例如…

读《数学之美》

数学之美 数学的发展实际上是不断的抽象和概括的过程 目录 数学之美 第一章 第二章&#xff08;从规则到统计&#xff09; 第三章 统计语言模型 第四章 分词 第五章 隐马尔科夫模型 第六章 信息的度量和作用 第七章 贾里尼克和和现代语言处理 第八章 简单之美——布…

java.lang.NoClassDefFoundError: org/apache/shiro/authc/AuthenticationToken

使用ieda构建web工程项目&#xff0c;启动tomcat报错&#xff1a; java.lang.NoClassDefFoundError: org/apache/shiro/authc/AuthenticationToken maven经过不断的clean&#xff0c;compile、package都没有作用&#xff0c;最后发现是因为compile后生成了jar包 于是手动在pom…

iOS屏幕尺寸和分辨率了解

1、截至目前为止&#xff0c;主流的iOS设备屏幕有以下几种&#xff1a; --------------- iPhone ---------- -------- iPad ------------ 2、iOS设备屏幕分辨率&#xff1a;&#xff08;ppi是像素密度单位【像素/英寸】&#xff0c;401ppi表示每英寸上有401个像素&#xff0…

java死锁检测

/*** author&#xff1a;cp* time&#xff1a;2021-2-24* Description: java死锁测试* 进程id查看命令&#xff1a;jsp 找到对应的进程id* 通过jstack 进程id 输出死锁信息** 如何定位死循环导致的其他线程阻塞等待&#xff1a;* linux下top命令查看cpu使用率较高的java进程&am…

spring技术内幕——深入解析spring架构与设计原理

林纳斯托瓦兹&#xff08;Linus Torvalds&#xff09;说&#xff1a;“我从心底认为&#xff0c;优秀的程序员与平庸的程序员之间的区别&#xff0c;是在于认为自己的代码重要还是数据结构更加重要。平庸的程序员眼里只有代码&#xff0c;优秀的程序员则关注数据结构及之前的关…