├── .gitignore
├── .idea
├── caches
│ └── build_file_checksums.ser
├── codeStyles
│ └── Project.xml
├── gradle.xml
├── inspectionProfiles
│ └── Project_Default.xml
├── misc.xml
├── runConfigurations.xml
└── vcs.xml
├── LICENSE
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── zjun
│ │ └── demo
│ │ └── ruleview
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── zjun
│ │ │ └── demo
│ │ │ └── ruleview
│ │ │ └── MainActivity.java
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ ├── ic_launcher_background.xml
│ │ └── shape_time_rule_view_bg.xml
│ │ ├── layout
│ │ └── activity_main.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── zjun
│ └── demo
│ └── ruleview
│ └── ExampleUnitTest.java
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── img
├── all.gif
├── money.gif
├── ruleView.gif
└── time.gif
├── rule-view
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── zjun
│ │ └── widget
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── zjun
│ │ │ └── widget
│ │ │ ├── MoneySelectRuleView.java
│ │ │ ├── RuleView.java
│ │ │ └── TimeRuleView.java
│ └── res
│ │ └── values
│ │ ├── attrs.xml
│ │ └── strings.xml
│ └── test
│ └── java
│ └── com
│ └── zjun
│ └── widget
│ └── ExampleUnitTest.java
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/libraries
5 | /.idea/modules.xml
6 | /.idea/workspace.xml
7 | .DS_Store
8 | /build
9 | /captures
10 | .externalNativeBuild
11 |
--------------------------------------------------------------------------------
/.idea/caches/build_file_checksums.ser:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjun615/RulerView/62273961c51dca1cb1f6eca699e3acb1ee352f29/.idea/caches/build_file_checksums.ser
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
18 |
19 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # RuleView
2 | [  ](https://bintray.com/zjun615/zjun/RuleView/_latestVersion)
3 |
4 | 一系列卷尺控件,包含:基本卷尺控件(体重尺,或其它)、金额卷尺控件、时间卷尺控件
5 |
6 | demo中,分别用三个控件,高仿了薄荷健康的体重尺、团贷网的金额尺、海康威视下萤石云视频的时间尺
7 |
8 | ## 一、效果图
9 | > 全部效果:
10 |
11 | 
12 |
13 | > RuleView:
14 |
15 | 
16 |
17 | > MoneySelectRuleView:
18 |
19 | 
20 |
21 | > TimeRuleView:
22 |
23 | 
24 |
25 |
26 | ## 二、卷尺功能说明
27 |
28 | ### 1. RuleView
29 |
30 | 基本卷尺控件,主要功能:
31 |
32 | - 手动滑动
33 | - 惯性滑动
34 | - 停止后,自动定位到最近的刻度
35 | - 支持动态修改最小值、最大值、当前值
36 |
37 | demo中以体重尺为例,但不限于此
38 |
39 | ### 2. MoneySelectRuleView
40 | 金额选择尺,除了基本卷尺的功能外,额外的功能有:
41 |
42 | - 可设置“剩余金额”
43 |
44 | ### 3. TimeRuleView
45 | 时间尺,一天24h内的时间尺,最小刻度是1s
46 |
47 | - 支持惯性滑动
48 | - 支持缩放时间刻度
49 | - 支持多个时间段的显示
50 |
51 | ## 三、依赖
52 | > build.gradle in app, the repertory is JCenter:
53 |
54 | `implementation 'com.zjun:rule-view:0.0.1'`
55 |
56 | ## 四、使用
57 |
58 | ### 4.1 布局
59 |
60 | 都是最简单的使用,根据需要使用自定义属性即可,详细的自定义属性见五
61 |
62 | ```xml
63 |
67 |
68 |
71 |
72 |
75 | ```
76 |
77 | ### 4.2 监听回调
78 |
79 | 主要用来监听当前数值的变化
80 | ```java
81 | ruleView.setOnValueChangedListener(new RuleView.OnValueChangedListener() {
82 | @Override
83 | public void onValueChanged(float value) {
84 | tvValue.setText(Float.toString(value));
85 | }
86 | });
87 |
88 | // 金额的超额判断,不在自定义View中判断,使用时自行判断,可参考demo
89 | moneySelectRuleView.setOnValueChangedListener(new MoneySelectRuleView.OnValueChangedListener() {
90 | @Override
91 | public void onValueChanged(int newValue) {
92 | tvMoney.setText(Integer.toString(newValue));
93 | }
94 | });
95 |
96 | timeRuleView.setOnTimeChangedListener(new TimeRuleView.OnTimeChangedListener() {
97 | @Override
98 | public void onTimeChanged(int newTimeValue) {
99 | tvTime.setText(TimeRuleView.formatTimeHHmmss(newTimeValue));
100 | }
101 | });
102 | ```
103 |
104 | ## 五、属性说明
105 |
106 | ### 5.1 RuleView属性
107 |
108 | 属性名 | 说明 | 默认值
109 | :------ | :------ | :------
110 | zjun_bgColor | 背景颜色 | #f5f8f5
111 | zjun_gradationColor | 刻度颜色 | Color.LTGRAY(#CCCCCC)
112 | gv_shortLineWidth | 短刻度线的宽度 | 1dp
113 | gv_shortGradationLen | 短刻度长度 | 16dp
114 | gv_longGradationLen | 长刻度长度 | gv_shortGradationLen * 2
115 | gv_longLineWidth | 长刻度线的宽度 | gv_shortLineWidth * 2
116 | zjun_textColor | 刻度值字体颜色 | Color.BLACK,#000000
117 | zjun_textSize | 刻度值字体大小 | 14sp
118 | zjun_indicatorLineColor | 中间指针线的颜色 | #48b975
119 | zjun_indicatorLineWidth | 中间指针线的宽度 | 3dp
120 | gv_indicatorLineLen | 中间指针线的长度 | 35dp
121 | gv_minValue | 最小值 | 0f
122 | gv_maxValue | 最大值 | 100f
123 | gv_currentValue | 当前值 | 50f
124 | gv_gradationUnit | 刻度间最小单位数值 | .1f
125 | gv_numberPerCount | 两数值间最小单位的个数 | 10
126 | gv_gradationGap | 最小单位的间距 | 10dp
127 | gv_gradationNumberGap | 数值与最长刻度的间距 | 8dp
128 |
129 |
130 | ### 5.2 MoneySelectRuleView属性
131 |
132 | 属性名 | 说明 | 默认值
133 | :------ | :------ | :------
134 | zjun_bgColor | 背景色 | #F5F5F5
135 | zjun_gradationColor | 刻度颜色 | Color.LTGRAY(#CCCCCC)
136 | msrv_gradationHeight | 刻度的总高度,刻度基线以上的高度 | 40dp
137 | msrv_gradationShortLen | 短刻度的长度 | 6dp
138 | msrv_gradationLongLen | 长刻度的长度 | msrv_gradationShortLen * 2
139 | msrv_gradationShortWidth | 短刻度的宽度 | 1px
140 | msrv_gradationLongWidth | 短刻度的长度 | msrv_gradationShortWidth
141 | msrv_gradationValueGap | 刻度数值与长刻度的间距 | 8dp
142 | msrv_gradationTextSize | 刻度数值文字的大小 | 12sp
143 | zjun_textColor | 刻度数值文字的颜色 | Color.GRAY
144 | zjun_indicatorLineColor | 中间指针线的颜色 | #eb4c1c
145 | msrv_balanceTextSize | 余额文字的大小 | 10sp
146 | msrv_unitGap | 最小单位的间距 | 6dp
147 | msrv_balanceText | 余额文字内容 | "剩余额度"
148 | msrv_balanceGap | 余额文字与刻度基线的间距 | 4dp
149 | msrv_maxValue | 最大金额 | 50_000
150 | msrv_currentValue | 当前金额 | 0
151 | msrv_balanceValue | 剩余金额 | 0
152 | msrv_valueUnit | 每隔最小单位代表的金额值 | 100
153 | msrv_valuePerCount | 刻度数值间的最小单位数 | 10
154 |
155 | ### 5.3 TimeRuleView属性
156 |
157 | 属性名 | 说明 | 默认值
158 | :------ | :------ | :------
159 | zjun_bgColor | 背景颜色 | #EEEEEE
160 | zjun_gradationColor | 刻度颜色 | Color.GRAY
161 | trv_partHeight | 时间段的高度 | 20dp
162 | trv_partColor | 时间的颜色 | #F58D24
163 | trv_gradationWidth | 刻度的宽度 | 1px
164 | trv_secondLen | 秒刻度的长度 | 3dp
165 | trv_minuteLen | 分刻度的长度 | 5dp
166 | trv_hourLen | 时刻度的长度 | 10dp
167 | trv_gradationTextColor | 刻度数值颜色 | Color.GRAY
168 | trv_gradationTextSize | 刻度数值字体大小 | 12sp
169 | trv_gradationTextGap | 刻度数值与时刻度的间距 | 2dp
170 | trv_currentTime | 当前时间 | 0(单位:秒,范围∈[0, 24*3600])
171 | trv_indicatorTriangleSideLen | 中间指针头部三角形的边长 | 15dp
172 | zjun_indicatorLineWidth | 中间指针的宽度 | 1dp
173 | zjun_indicatorLineColor | 中间指针的颜色 | Color.RED
174 |
175 | ## 六、参考
176 |
177 | [1] [带你实现漂亮的滑动卷尺](https://mp.weixin.qq.com/s?__biz=MzIyNTY4NjU0OQ==&mid=2247485213&idx=1&sn=97fb5d0645f0bb0eb2c5c51db4454b59&chksm=e87aa267df0d2b71d53fa2267b12afae265df585246e8ce5e2edc32d9c57bad6fbd78ec0469c&mpshare=1&scene=23&srcid=0717uZbDuuzfAGiZKvVaft9k#rd)
178 |
179 | [2] [安卓自定义View进阶-缩放手势检测(ScaleGestureDecetor)](http://www.gcssloop.com/customview/scalegesturedetector)
180 |
181 | [3] [安卓自定义View进阶-MotionEvent详解](http://www.gcssloop.com/customview/motionevent)
182 |
183 | [4] [手把手教你发布自己的开源库到 Jcenter](https://mp.weixin.qq.com/s?__biz=MzIwMTAzMTMxMg==&mid=2649492998&idx=1&sn=015de305fa8cb125caf25d072165f6e8&chksm=8eec85f9b99b0cef30052e7333129ee1ffbba1600ebe5529b05c7d67a7690438ae7180acc804&mpshare=1&scene=23&srcid=0818WK605Hl5ctCkIBFtDP5q#rd)
184 |
185 | [5] RecyclerView 的 onTouchEvent(MotionEvent e) 源码
186 |
187 | **说明:**
188 |
189 | RuleView,针对参考[1]中 TapeView 的源码,进行了一些优化:
190 |
191 | 1) 左侧起始绘制刻度:如果当前绘制的刻度 currentCalibration 为0,即第一个刻度,则不绘制。滑动过程中,会发现最左侧的刻度,有时会突然消失。如果此刻度是带数值的长刻度,那数值也不会显示,界面突变会更明显。把控件宽度为 gapWidth 的整数倍,能立马看到这突变效果
192 |
193 | 优化:左侧起始刻度,往左多绘制2个刻度单位
194 |
195 | 2) 右侧结束绘制刻度:一直绘制到当前控件的10倍宽,或最大刻度数(totalCalibration = 最大刻度数 + 1,看的时候掉坑了,觉得最大刻度绘制不出来,原来是加了1)
196 |
197 | 优化:在最大刻度内,右侧结束刻度,与左侧起始刻度一样,多绘制2个刻度单位即可
198 |
199 | 多绘制的刻度单位个数,完全可以根据数值的最大宽度来决定。多了2个刻度单位,因为数值与刻度对称,就有了4个刻度。具体根据项目,多退少补
200 |
201 | ## 七、更新
202 | > *2018/8/22*:
203 |
204 | 经过网友提醒,才发现单词 Rule 写错了,尴尬了⁄(⁄ ⁄•⁄ω⁄•⁄ ⁄)⁄。现更改 GitHub 项目名为 RulerView,其它不便修改,保持不变。
205 |
206 | ## 八、LICENSE
207 | ```
208 | Copyright (c) 2018 Ralap
209 |
210 | Licensed under the Apache License, Version 2.0 (the "License");
211 | you may not use this file except in compliance with the License.
212 | You may obtain a copy of the License at
213 |
214 | http://www.apache.org/licenses/LICENSE-2.0
215 |
216 | Unless required by applicable law or agreed to in writing, software
217 | distributed under the License is distributed on an "AS IS" BASIS,
218 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
219 | See the License for the specific language governing permissions and
220 | limitations under the License.
221 | ```
222 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 27
5 | defaultConfig {
6 | applicationId "com.zjun.demo.ruleview"
7 | minSdkVersion 16
8 | targetSdkVersion 27
9 | versionCode 1
10 | versionName "1.0"
11 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | }
20 |
21 | dependencies {
22 | implementation fileTree(include: ['*.jar'], dir: 'libs')
23 | implementation 'com.android.support:appcompat-v7:27.1.1'
24 | implementation 'com.android.support.constraint:constraint-layout:1.1.2'
25 | implementation 'com.android.support:design:27.1.1'
26 | testImplementation 'junit:junit:4.12'
27 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
28 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
29 | implementation project(':rule-view')
30 | }
31 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/zjun/demo/ruleview/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.zjun.demo.ruleview;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumented test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.zjun.demo.gradationview", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/java/com/zjun/demo/ruleview/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.zjun.demo.ruleview;
2 |
3 | import android.os.Bundle;
4 | import android.support.annotation.IdRes;
5 | import android.support.design.widget.Snackbar;
6 | import android.support.v7.app.AppCompatActivity;
7 | import android.view.View;
8 | import android.widget.EditText;
9 | import android.widget.LinearLayout;
10 | import android.widget.TextView;
11 |
12 | import com.zjun.widget.MoneySelectRuleView;
13 | import com.zjun.widget.RuleView;
14 | import com.zjun.widget.TimeRuleView;
15 |
16 | import java.util.ArrayList;
17 | import java.util.List;
18 | import java.util.Random;
19 |
20 | public class MainActivity extends AppCompatActivity {
21 |
22 | private TextView tvValue;
23 | private RuleView gvRule;
24 | private MoneySelectRuleView msrvMoney;
25 | private TextView tvMoney;
26 | private EditText etMoney;
27 | private TimeRuleView trvTime;
28 | private TextView tvTime;
29 |
30 | private float moneyBalance;
31 | private boolean isMoneySloped;
32 |
33 | @Override
34 | protected void onCreate(Bundle savedInstanceState) {
35 | super.onCreate(savedInstanceState);
36 | setContentView(R.layout.activity_main);
37 |
38 | tvTime = findViewById(R.id.tv_time);
39 | trvTime = findViewById(R.id.trv_time);
40 | tvMoney = findViewById(R.id.tv_money);
41 | etMoney = findViewById(R.id.et_new_money);
42 | msrvMoney = findViewById(R.id.msrv_money);
43 | tvValue = findViewById(R.id.tv_value);
44 | gvRule = findViewById(R.id.gv_1);
45 |
46 |
47 | tvValue.setText(Float.toString(gvRule.getCurrentValue()));
48 | gvRule.setOnValueChangedListener(new RuleView.OnValueChangedListener() {
49 | @Override
50 | public void onValueChanged(float value) {
51 | tvValue.setText(Float.toString(value));
52 | }
53 | });
54 |
55 | tvMoney.setText(Integer.toString(msrvMoney.getValue()));
56 | moneyBalance = msrvMoney.getBalance();
57 | msrvMoney.setOnValueChangedListener(new MoneySelectRuleView.OnValueChangedListener() {
58 | @Override
59 | public void onValueChanged(int newValue) {
60 | tvMoney.setText(Integer.toString(newValue));
61 | if (newValue > moneyBalance) {
62 | if (!isMoneySloped) {
63 | isMoneySloped = true;
64 | Snackbar.make(msrvMoney, "超出额度", Snackbar.LENGTH_SHORT).show();
65 | }
66 | } else {
67 | if (isMoneySloped) {
68 | isMoneySloped = false;
69 | }
70 | }
71 | }
72 | });
73 |
74 | trvTime.setOnTimeChangedListener(new TimeRuleView.OnTimeChangedListener() {
75 | @Override
76 | public void onTimeChanged(int newTimeValue) {
77 | tvTime.setText(TimeRuleView.formatTimeHHmmss(newTimeValue));
78 | }
79 | });
80 | // 模拟时间段数据
81 | List list = new ArrayList<>();
82 | for (int i = 0; i < 10; i++) {
83 | TimeRuleView.TimePart part = new TimeRuleView.TimePart();
84 | part.startTime = i * 1000;
85 | part.endTime = part.startTime + new Random().nextInt(1000);
86 | list.add(part);
87 | }
88 | trvTime.setTimePartList(list);
89 |
90 | }
91 |
92 |
93 | public void onClick(View view) {
94 | switch (view.getId()) {
95 | case R.id.tv_rule_indicator:
96 | toggleSettingsShow(R.id.ll_rule_settings);
97 | break;
98 | case R.id.btn_50:
99 | gvRule.setCurrentValue(gvRule.getMinValue() == 11 ? 15 : 50);
100 | break;
101 | case R.id.btn_change:
102 | toggleValue();
103 | break;
104 | case R.id.tv_money_indicator:
105 | toggleSettingsShow(R.id.ll_money_settings);
106 | break;
107 | case R.id.btn_set_money:
108 | float money = getMoney();
109 | msrvMoney.setValue(money);
110 | break;
111 | case R.id.btn_set_balance:
112 | moneyBalance = getMoney();
113 | msrvMoney.setBalance(moneyBalance);
114 | isMoneySloped = false;
115 | break;
116 | default: break;
117 | }
118 | }
119 |
120 | private void toggleSettingsShow(@IdRes int layoutId) {
121 | LinearLayout llSettings = findViewById(layoutId);
122 | llSettings.setVisibility(llSettings.getVisibility() == View.VISIBLE ? View.INVISIBLE : View.VISIBLE);
123 | }
124 |
125 | private void toggleValue() {
126 | if (gvRule.getMinValue() == 11) {
127 | gvRule.setValue(0, 100, 50, 0.1f, 10);
128 | } else {
129 | gvRule.setValue(11, 20, 15, 0.2f, 5);
130 | }
131 | }
132 |
133 | private float getMoney() {
134 | String moneyStr = etMoney.getText().toString();
135 | if (moneyStr.isEmpty()) {
136 | moneyStr = "0";
137 | }
138 | return Float.parseFloat(moneyStr);
139 | }
140 |
141 | }
142 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/shape_time_rule_view_bg.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
8 |
9 |
10 |
11 |
12 |
13 |
16 |
17 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
12 |
17 |
18 |
25 |
26 |
34 |
35 |
45 |
46 |
47 |
53 |
54 |
60 |
61 |
65 |
66 |
74 |
75 |
82 |
83 |
84 |
85 |
89 |
90 |
97 |
98 |
107 |
108 |
109 |
110 |
114 |
115 |
121 |
122 |
126 |
127 |
136 |
137 |
146 |
147 |
156 |
157 |
158 |
164 |
165 |
170 |
171 |
181 |
182 |
183 |
187 |
188 |
189 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjun615/RulerView/62273961c51dca1cb1f6eca699e3acb1ee352f29/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjun615/RulerView/62273961c51dca1cb1f6eca699e3acb1ee352f29/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjun615/RulerView/62273961c51dca1cb1f6eca699e3acb1ee352f29/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjun615/RulerView/62273961c51dca1cb1f6eca699e3acb1ee352f29/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjun615/RulerView/62273961c51dca1cb1f6eca699e3acb1ee352f29/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjun615/RulerView/62273961c51dca1cb1f6eca699e3acb1ee352f29/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjun615/RulerView/62273961c51dca1cb1f6eca699e3acb1ee352f29/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjun615/RulerView/62273961c51dca1cb1f6eca699e3acb1ee352f29/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjun615/RulerView/62273961c51dca1cb1f6eca699e3acb1ee352f29/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjun615/RulerView/62273961c51dca1cb1f6eca699e3acb1ee352f29/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | RuleView
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/zjun/demo/ruleview/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.zjun.demo.ruleview;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 |
18 | @Test
19 | public void testIt() {
20 | float[] nums = {
21 | 6,
22 | 3.005821f,
23 | 0.022f,
24 | 0.0188f,
25 | 0.56f,
26 | 1f,
27 | 0.3f,
28 | 0.9f,
29 | 1.5f,
30 | 1.7f,
31 | 2.0f,
32 | 5f,
33 | 0.0001f,
34 | };
35 |
36 | for (float num : nums) {
37 | println("%f =%d", num, getScaleIndex(num));
38 | }
39 | }
40 |
41 | private float[] mPerCountScaleThresholds = {
42 | 6f, 3.6f, 1.8f, 1.5f, // 10s/unit: 最大值, 1min, 2min, 4min
43 | 0.8f, 0.4f, // 1min/unit: 5min, 10min
44 | 0.25f, 0.125f, // 5min/unit: 20min, 30min
45 | 0.07f, 0.04f, 0.03f, 0.025f, 0.02f, 0.015f // 15min/unit: 1h, 2h, 3h, 4h, 5h, 6h
46 | };
47 |
48 | private int getScaleIndex(float scale) {
49 | final int size = mPerCountScaleThresholds.length;
50 | int min = 0;
51 | int max = size - 1;
52 | int mid = (min + max) >> 1;
53 | // println("min=%d, max=%d, mid=%d", min, max, mid);
54 | while (!(scale >= mPerCountScaleThresholds[mid] && scale < mPerCountScaleThresholds[mid - 1])) {
55 | if (scale >= mPerCountScaleThresholds[mid - 1]) {
56 | // 因为往大取,所以不修改为mid -1
57 | max = mid;
58 | } else {
59 | min = mid + 1;
60 | }
61 | // println("min=%d, max=%d, mid=%d", min, max, mid);
62 | mid = (min + max) >> 1;
63 | if (min == max) {
64 | break;
65 | }
66 | if (mid == 0) {
67 | break;
68 | }
69 | }
70 | return mid;
71 | }
72 |
73 | private void println(String format, Object... args) {
74 | System.out.println(String.format(format, args));
75 | }
76 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 |
5 | repositories {
6 | google()
7 | jcenter()
8 | }
9 | dependencies {
10 | classpath 'com.android.tools.build:gradle:3.1.4'
11 |
12 |
13 | // NOTE: Do not place your application dependencies here; they belong
14 | // in the individual module build.gradle files
15 |
16 | // bintray: 加上这两行
17 | classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
18 | classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.4'
19 | }
20 | }
21 |
22 | allprojects {
23 | repositories {
24 | google()
25 | jcenter()
26 | }
27 | }
28 |
29 | task clean(type: Delete) {
30 | delete rootProject.buildDir
31 | }
32 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjun615/RulerView/62273961c51dca1cb1f6eca699e3acb1ee352f29/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sun Jul 29 10:00:38 CST 2018
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/img/all.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjun615/RulerView/62273961c51dca1cb1f6eca699e3acb1ee352f29/img/all.gif
--------------------------------------------------------------------------------
/img/money.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjun615/RulerView/62273961c51dca1cb1f6eca699e3acb1ee352f29/img/money.gif
--------------------------------------------------------------------------------
/img/ruleView.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjun615/RulerView/62273961c51dca1cb1f6eca699e3acb1ee352f29/img/ruleView.gif
--------------------------------------------------------------------------------
/img/time.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zjun615/RulerView/62273961c51dca1cb1f6eca699e3acb1ee352f29/img/time.gif
--------------------------------------------------------------------------------
/rule-view/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/rule-view/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | // bintray: 添加这两行
4 | apply plugin: 'com.github.dcendents.android-maven'
5 | apply plugin: 'com.jfrog.bintray'
6 |
7 | android {
8 | compileSdkVersion 27
9 |
10 |
11 |
12 | defaultConfig {
13 | minSdkVersion 16
14 | targetSdkVersion 27
15 | versionCode 1
16 | versionName "1.0"
17 |
18 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
19 |
20 | }
21 |
22 | buildTypes {
23 | release {
24 | minifyEnabled false
25 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
26 | }
27 | }
28 |
29 | }
30 |
31 | dependencies {
32 | implementation fileTree(dir: 'libs', include: ['*.jar'])
33 |
34 | implementation 'com.android.support:appcompat-v7:27.1.1'
35 | testImplementation 'junit:junit:4.12'
36 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
37 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
38 | }
39 |
40 |
41 |
42 | // ===============以下都是binary的配置================
43 | //项目主页
44 | def siteUrl = 'https://github.com/zjun615/RuleView'
45 | //项目的git地址
46 | def gitUrl = 'https://github.com/zjun615/RuleView.git'
47 | //发布到JCenter上的项目名字
48 | def libName = "RuleView"
49 |
50 | //发布到组织名称名字,必须填写
51 | //(com.ssy.fireworkstextview)这样写是不好的,项目名会拼上去
52 | //我手欠然后最后就是这样了,大家引以为戒
53 | //compile 'com.ssy.fireworkstextview:fireworkstextview:1.0.0'
54 | group = "com.zjun"
55 | // 版本号,下次更新是只需要更改版本号即可
56 | version = "0.0.1"
57 | //上面配置后上传至JCenter后的编译路径是这样的: compile 'me.songning.CircleView:library:1.0.0'
58 |
59 | //生成源文件
60 | task sourcesJar(type: Jar) {
61 | from android.sourceSets.main.java.srcDirs
62 | classifier = 'sources'
63 | }
64 |
65 | //生成Javadoc文档
66 | task javadoc(type: Javadoc) {
67 | source = android.sourceSets.main.java.srcDirs
68 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
69 | }
70 |
71 | //文档打包成jar
72 | task javadocJar(type: Jar, dependsOn: javadoc) {
73 | classifier = 'javadoc'
74 | from javadoc.destinationDir
75 | }
76 |
77 | //拷贝javadoc文件
78 | task copyDoc(type: Copy) {
79 | from "${buildDir}/docs/"
80 | into "docs"
81 | }
82 |
83 | //上传到JCenter所需要的源码文件
84 | artifacts {
85 | archives javadocJar
86 | archives sourcesJar
87 | }
88 |
89 | // 配置maven库,生成POM.xml文件
90 | install {
91 | repositories.mavenInstaller {
92 | // This generates POM.xml with proper parameters
93 | pom {
94 | project {
95 | packaging 'aar'
96 | //项目描述,随意填
97 | name 'A series of rule views, eg: weight, money, time, and so on'
98 | url siteUrl
99 | licenses {
100 | license {
101 | //开源协议
102 | name 'The Apache Software License, Version 2.0'
103 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
104 | }
105 | }
106 | developers {
107 | developer {
108 | //开发者的个人信息
109 | id 'zjun615'
110 | name 'RalapZhong'
111 | email 'zjun2pst@gmail.com'
112 | }
113 | }
114 | scm {
115 | connection gitUrl
116 | developerConnection gitUrl
117 | url siteUrl
118 | }
119 | }
120 | }
121 | }
122 | }
123 |
124 | //上传到JCenter
125 | Properties properties = new Properties()
126 | properties.load(project.rootProject.file('local.properties').newDataInputStream())
127 |
128 | bintray {
129 | user = properties.getProperty("bintray.user") //读取 local.properties 文件里面的 bintray.user
130 | key = properties.getProperty("bintray.apikey") //读取 local.properties 文件里面的 bintray.apikey
131 | configurations = ['archives']
132 | pkg {
133 | //注意:这里的repo值必须要和你创建Maven仓库的时候的名字一样
134 | repo = "zjun"
135 | //发布到JCenter上的项目名字
136 | name = libName
137 | //项目描述
138 | desc = 'A series of rule views, eg: weight, money, time, and so on'
139 | websiteUrl = siteUrl
140 | vcsUrl = gitUrl
141 | licenses = ["Apache-2.0"]
142 | publish = true
143 | }
144 | }
145 |
146 | javadoc {
147 | options{
148 | //如果你的项目里面有中文注释的话,必须将格式设置为UTF-8,不然会出现乱码
149 | encoding "UTF-8"
150 | charSet 'UTF-8'
151 | author true
152 | version true
153 | links "http://docs.oracle.com/javase/7/docs/api"
154 | }
155 | }
--------------------------------------------------------------------------------
/rule-view/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/rule-view/src/androidTest/java/com/zjun/widget/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.zjun.widget;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumented test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.zjun.widget.test", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/rule-view/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
--------------------------------------------------------------------------------
/rule-view/src/main/java/com/zjun/widget/MoneySelectRuleView.java:
--------------------------------------------------------------------------------
1 | package com.zjun.widget;
2 |
3 | import android.content.Context;
4 | import android.content.res.TypedArray;
5 | import android.graphics.Canvas;
6 | import android.graphics.Color;
7 | import android.graphics.Paint;
8 | import android.support.annotation.Nullable;
9 | import android.text.TextPaint;
10 | import android.text.TextUtils;
11 | import android.util.AttributeSet;
12 | import android.util.Log;
13 | import android.util.TypedValue;
14 | import android.view.MotionEvent;
15 | import android.view.VelocityTracker;
16 | import android.view.View;
17 | import android.view.ViewConfiguration;
18 | import android.widget.Scroller;
19 |
20 | /**
21 | * MoneySelectRuleView
22 | * 金额选择卷尺控件
23 | *
24 | * 每隔固定100
25 | *
26 | * 参考:{@link RuleView}
27 | *
28 | * Author: Ralap
29 | * Description:
30 | * Date 2018/8/9
31 | */
32 | public class MoneySelectRuleView extends View {
33 |
34 | private static final boolean LOG_ENABLE = BuildConfig.DEBUG;
35 |
36 | /**
37 | * 滑动阈值
38 | */
39 | private final int TOUCH_SLOP;
40 | /**
41 | * 惯性滑动最小、最大速度
42 | */
43 | private final int MIN_FLING_VELOCITY;
44 | private final int MAX_FLING_VELOCITY;
45 |
46 | private int bgColor;
47 | private int gradationColor;
48 | private float gradationHeight;
49 | private float gradationShortLen;
50 | private float gradationLongLen;
51 | private float gradationShortWidth;
52 | private float gradationLongWidth;
53 | private float gradationValueGap;
54 | private float gradationTextSize;
55 | private int gradationTextColor;
56 |
57 | private float balanceTextSize;
58 | private int indicatorColor;
59 | private float unitGap;
60 |
61 | private String balanceText;
62 | private float balanceGap;
63 |
64 | private int maxValue;
65 | private int currentValue;
66 | private int balanceValue;
67 | private int valueUnit;
68 | private int valuePerCount;
69 |
70 |
71 | private float mCurrentDistance;
72 | private int mWidthRangeValue;
73 | private int mRangeDistance;
74 |
75 | private int mWidth, mHeight, mHalfWidth;
76 | private Paint mPaint;
77 | private TextPaint mTextPaint;
78 | private Scroller mScroller;
79 | private VelocityTracker mVelocityTracker;
80 | private OnValueChangedListener mListener;
81 |
82 | public interface OnValueChangedListener {
83 | /**
84 | * 当值变化时调用
85 | * @param newValue 变化后的新值
86 | */
87 | void onValueChanged(int newValue);
88 |
89 | }
90 |
91 | public MoneySelectRuleView(Context context) {
92 | this(context, null);
93 | }
94 |
95 | public MoneySelectRuleView(Context context, @Nullable AttributeSet attrs) {
96 | this(context, attrs, 0);
97 | }
98 |
99 | public MoneySelectRuleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
100 | super(context, attrs, defStyleAttr);
101 | initAttrs(context, attrs);
102 |
103 | // 初始化final常量,必须在构造中赋初值
104 | ViewConfiguration viewConfiguration = ViewConfiguration.get(context);
105 | TOUCH_SLOP = viewConfiguration.getScaledTouchSlop();
106 | MIN_FLING_VELOCITY = viewConfiguration.getScaledMinimumFlingVelocity();
107 | MAX_FLING_VELOCITY = viewConfiguration.getScaledMaximumFlingVelocity();
108 |
109 | calculateValues();
110 | init(context);
111 | }
112 |
113 | private void calculateValues() {
114 | mCurrentDistance = (float) currentValue / valueUnit * unitGap;
115 | mRangeDistance = (int) (maxValue / valueUnit * unitGap);
116 | mWidthRangeValue = (int) (mWidth / unitGap * valueUnit);
117 | }
118 |
119 | private void init(Context context) {
120 | mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
121 | mPaint.setColor(gradationColor);
122 |
123 | mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
124 | mTextPaint.setTextSize(balanceTextSize);
125 | mTextPaint.setColor(gradationTextColor);
126 |
127 | mScroller = new Scroller(context);
128 |
129 | mVelocityTracker = VelocityTracker.obtain();
130 | }
131 |
132 | private void initAttrs(Context context, AttributeSet attrs) {
133 | TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MoneySelectRuleView);
134 | bgColor = ta.getColor(R.styleable.MoneySelectRuleView_zjun_bgColor, Color.parseColor("#F5F5F5"));
135 | gradationColor = ta.getColor(R.styleable.MoneySelectRuleView_zjun_gradationColor, Color.LTGRAY);
136 | gradationHeight = ta.getDimension(R.styleable.MoneySelectRuleView_msrv_gradationHeight, dp2px(40));
137 | gradationShortLen = ta.getDimension(R.styleable.MoneySelectRuleView_msrv_gradationShortLen, dp2px(6));
138 | gradationLongLen = ta.getDimension(R.styleable.MoneySelectRuleView_msrv_gradationLongLen, gradationShortLen * 2);
139 | gradationShortWidth = ta.getDimension(R.styleable.MoneySelectRuleView_msrv_gradationShortWidth, 1);
140 | gradationLongWidth = ta.getDimension(R.styleable.MoneySelectRuleView_msrv_gradationLongWidth, gradationShortWidth);
141 | gradationValueGap = ta.getDimension(R.styleable.MoneySelectRuleView_msrv_gradationValueGap, dp2px(8));
142 | gradationTextSize = ta.getDimension(R.styleable.MoneySelectRuleView_msrv_gradationTextSize, sp2px(12));
143 | gradationTextColor = ta.getColor(R.styleable.MoneySelectRuleView_zjun_textColor, Color.GRAY);
144 | indicatorColor = ta.getColor(R.styleable.MoneySelectRuleView_zjun_indicatorLineColor, Color.parseColor("#eb4c1c"));
145 | balanceTextSize = ta.getDimension(R.styleable.MoneySelectRuleView_msrv_balanceTextSize, sp2px(10));
146 | unitGap = ta.getDimension(R.styleable.MoneySelectRuleView_msrv_unitGap, dp2px(6));
147 | balanceText = ta.getString(R.styleable.MoneySelectRuleView_msrv_balanceText);
148 | if (TextUtils.isEmpty(balanceText)) {
149 | balanceText = context.getString(R.string.balance_text);
150 | }
151 | balanceGap = ta.getDimension(R.styleable.MoneySelectRuleView_msrv_balanceGap, dp2px(4));
152 | maxValue = ta.getInt(R.styleable.MoneySelectRuleView_msrv_maxValue, 50_000);
153 | currentValue = ta.getInt(R.styleable.MoneySelectRuleView_msrv_currentValue, 0);
154 | balanceValue = ta.getInt(R.styleable.MoneySelectRuleView_msrv_balanceValue, 0);
155 | valueUnit = ta.getInt(R.styleable.MoneySelectRuleView_msrv_valueUnit, 100);
156 | valuePerCount = ta.getInt(R.styleable.MoneySelectRuleView_msrv_valuePerCount, 10);
157 | ta.recycle();
158 | }
159 |
160 | @Override
161 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
162 | mWidth = MeasureSpec.getSize(widthMeasureSpec);
163 | mHalfWidth = mWidth >> 1;
164 | final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
165 | mHeight = MeasureSpec.getSize(heightMeasureSpec);
166 |
167 | if (heightMode == MeasureSpec.AT_MOST) {
168 | mHeight = dp2px(60);
169 | gradationHeight = dp2px(40);
170 | }
171 |
172 | mWidthRangeValue = (int) (mWidth / unitGap * valueUnit);
173 |
174 | setMeasuredDimension(mWidth, mHeight);
175 | }
176 |
177 | private int mDownX, mDownY;
178 | private int mLastX, mLastY;
179 | private boolean mIsMoving;
180 |
181 | @Override
182 | public boolean onTouchEvent(MotionEvent event) {
183 | final int action = event.getAction();
184 | final int x = (int) event.getX();
185 | final int y = (int) event.getY();
186 | if (mVelocityTracker == null) {
187 | mVelocityTracker = VelocityTracker.obtain();
188 | }
189 | mVelocityTracker.addMovement(event);
190 | logD("onTouchEvent: action=%d", action);
191 | switch (action) {
192 | case MotionEvent.ACTION_DOWN:
193 | mIsMoving = false;
194 | mDownX = x;
195 | mDownY = y;
196 | if (!mScroller.isFinished()) {
197 | mScroller.forceFinished(true);
198 | }
199 | break;
200 | case MotionEvent.ACTION_MOVE:
201 | final int dx = x - mLastX;
202 | if (!mIsMoving) {
203 | final int dy = y - mLastY;
204 | if (Math.abs(x - mDownX) <= TOUCH_SLOP || Math.abs(dx) < Math.abs(dy)) {
205 | break;
206 | }
207 | mIsMoving = true;
208 | }
209 | mCurrentDistance -= dx;
210 | computeValue();
211 | break;
212 | case MotionEvent.ACTION_UP:
213 | if (!mIsMoving) {
214 | break;
215 | }
216 | // 计算速度
217 | mVelocityTracker.computeCurrentVelocity(1000, MAX_FLING_VELOCITY);
218 | // 获取当前的水平速度
219 | int xVelocity = (int) mVelocityTracker.getXVelocity();
220 | logD("up: xVelocity=%d", xVelocity);
221 | if (Math.abs(xVelocity) < MIN_FLING_VELOCITY) {
222 | // 滑动刻度
223 | scrollToGradation();
224 | } else {
225 | // 惯性滑动。
226 | mScroller.fling((int) mCurrentDistance, 0, -xVelocity, 0, 0, mRangeDistance, 0, 0);
227 | invalidate();
228 | }
229 | break;
230 | case MotionEvent.ACTION_CANCEL:
231 | if (!mScroller.isFinished()) {
232 | // 结束滑动,并把数值立马置为终点值
233 | mScroller.abortAnimation();
234 | }
235 | break;
236 | default: break;
237 | }
238 | mLastX = x;
239 | mLastY = y;
240 | return true;
241 | }
242 |
243 | /**
244 | * 滑动到最近的刻度上
245 | */
246 | private void scrollToGradation() {
247 | // 最近的刻度
248 | currentValue = Math.round(mCurrentDistance / unitGap) * valueUnit;
249 | // 校验边界
250 | currentValue = Math.min(maxValue, Math.max(0, currentValue));
251 | // 计算新刻度位置
252 | mCurrentDistance = currentValue / valueUnit * unitGap;
253 | logD("scrollToGradation: currentValue=%d, mCurrentDistance=%f", currentValue, mCurrentDistance);
254 | if (mListener != null) {
255 | mListener.onValueChanged(currentValue);
256 | }
257 | invalidate();
258 | }
259 |
260 | /**
261 | * 校验距离,并重新计算当前值
262 | */
263 | private void computeValue() {
264 | logD("computeValue: mRangeDistance=%d, mCurrentDistance=%f", mRangeDistance, mCurrentDistance);
265 | mCurrentDistance = Math.min(mRangeDistance, Math.max(0, mCurrentDistance));
266 | currentValue = (int)(mCurrentDistance / unitGap) * valueUnit;
267 | if (mListener != null) {
268 | mListener.onValueChanged(currentValue);
269 | }
270 | postInvalidate();
271 | }
272 |
273 | @Override
274 | protected void onDraw(Canvas canvas) {
275 | // 背景
276 | canvas.drawColor(bgColor);
277 | // 刻度数值
278 | drawRule(canvas);
279 | // 绘制指针
280 | drawIndicator(canvas);
281 | }
282 |
283 | /**
284 | * 绘制刻度、金额、及剩余额度
285 | */
286 | private void drawRule(Canvas canvas) {
287 | canvas.save();
288 | canvas.translate(0, gradationHeight);
289 |
290 | // 参考线
291 | mPaint.setStrokeWidth(gradationShortWidth);
292 | canvas.drawLine(0, 0, mWidth, 0, mPaint);
293 |
294 | // 刻度、数值
295 | final int expend = 3 * valueUnit;
296 | // 起始绘制刻度
297 | int start = (int) ((mCurrentDistance - mHalfWidth) / unitGap) * valueUnit;
298 | start = Math.max(0, start - expend);
299 | int end = Math.min(maxValue, (start + expend) + mWidthRangeValue + expend);
300 | float startOffset = mHalfWidth - (mCurrentDistance - start / valueUnit * unitGap);
301 | final int perCount = valuePerCount * valueUnit;
302 | // 剩余金额:向下取整
303 | final int balance = balanceValue / valueUnit * valueUnit;
304 | logD("drawRule: mCurrentDistance=%f, start=%d, end=%d, startOffset=%f, perCount=%d",
305 | mCurrentDistance, start, end, startOffset, perCount);
306 | while (start <= end) {
307 | if (start % perCount == 0) {
308 | // 刻度
309 | mPaint.setStrokeWidth(gradationLongWidth);
310 | canvas.drawLine(startOffset, 0, startOffset, -gradationLongLen, mPaint);
311 |
312 | // 数值
313 | mTextPaint.setTextSize(gradationTextSize);
314 | mTextPaint.setColor(gradationTextColor);
315 | String text = Integer.toString(start);
316 | float textWidth = mTextPaint.measureText(text);
317 | canvas.drawText(text, startOffset - textWidth * .5f, -(gradationLongLen + gradationValueGap), mTextPaint);
318 | } else {
319 | mPaint.setStrokeWidth(gradationShortWidth);
320 | canvas.drawLine(startOffset, 0, startOffset, -gradationShortLen, mPaint);
321 | }
322 |
323 | // 剩余金额
324 | if (start == balance) {
325 | mPaint.setColor(indicatorColor);
326 | canvas.drawLine(startOffset, 0, startOffset, -gradationLongLen, mPaint);
327 | mPaint.setColor(gradationColor);
328 |
329 | mTextPaint.setTextSize(balanceTextSize);
330 | mTextPaint.setColor(indicatorColor);
331 | float textWidth = mTextPaint.measureText(balanceText);
332 | canvas.drawText(balanceText, startOffset - textWidth * .5f, balanceGap + balanceTextSize, mTextPaint);
333 | mTextPaint.setColor(gradationColor);
334 | }
335 |
336 | start += valueUnit;
337 | startOffset += unitGap;
338 | }
339 |
340 | canvas.restore();
341 | }
342 |
343 | @Override
344 | public void computeScroll() {
345 | if (mScroller.computeScrollOffset()) {
346 | if (mScroller.getCurrX() == mScroller.getFinalX()) {
347 | // 已经达到终点:滑动到刻度线上
348 | scrollToGradation();
349 | } else {
350 | mCurrentDistance = mScroller.getCurrX();
351 | computeValue();
352 | }
353 | }
354 | }
355 |
356 | /**
357 | * 绘制指针
358 | */
359 | private void drawIndicator(Canvas canvas) {
360 | mPaint.setColor(indicatorColor);
361 | canvas.drawLine(mHalfWidth, 0, mHalfWidth, gradationHeight, mPaint);
362 | mPaint.setColor(gradationColor);
363 | }
364 |
365 | private int dp2px(float dp) {
366 | return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
367 | }
368 |
369 | private int sp2px(float sp) {
370 | return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, getResources().getDisplayMetrics());
371 | }
372 |
373 | @SuppressWarnings("all")
374 | private void logD(String format, Object... args) {
375 | if (LOG_ENABLE) {
376 | Log.d("MoneySelectRuleView", String.format("zjun@" + format, args));
377 | }
378 | }
379 |
380 | public int getValue() {
381 | return currentValue;
382 | }
383 |
384 | /**
385 | * 设置值
386 | * 注意:这里不需要回调,否则会改变原数据
387 | *
388 | * @param value 当前金额
389 | */
390 | public void setValue(float value) {
391 | // 向下取整
392 | this.currentValue = (int) value / valueUnit * valueUnit;
393 | currentValue = Math.min(maxValue, Math.max(0, currentValue));
394 | if (!mScroller.isFinished()) {
395 | mScroller.forceFinished(true);
396 | }
397 | if (mListener != null) {
398 | mListener.onValueChanged(currentValue);
399 | }
400 | calculateValues();
401 | postInvalidate();
402 | }
403 |
404 | public int getBalance() {
405 | return balanceValue;
406 | }
407 |
408 | public void setBalance(float balance) {
409 | this.balanceValue = (int) balance / valueUnit * valueUnit;
410 | postInvalidate();
411 | }
412 |
413 | public void setOnValueChangedListener(OnValueChangedListener listener) {
414 | this.mListener = listener;
415 | }
416 | }
417 |
--------------------------------------------------------------------------------
/rule-view/src/main/java/com/zjun/widget/RuleView.java:
--------------------------------------------------------------------------------
1 | package com.zjun.widget;
2 |
3 |
4 | import android.content.Context;
5 | import android.content.res.TypedArray;
6 | import android.graphics.Canvas;
7 | import android.graphics.Color;
8 | import android.graphics.Paint;
9 | import android.support.annotation.Nullable;
10 | import android.text.TextPaint;
11 | import android.util.AttributeSet;
12 | import android.util.Log;
13 | import android.util.TypedValue;
14 | import android.view.MotionEvent;
15 | import android.view.VelocityTracker;
16 | import android.view.View;
17 | import android.view.ViewConfiguration;
18 | import android.view.ViewGroup;
19 | import android.widget.Scroller;
20 |
21 | /**
22 | * GradationView
23 | * 刻度卷尺控件
24 | *
25 | * 思路:
26 | * 1. 把float类型数据,乘10,转为int类型。之所以把它放在第一位,因为踩过这个坑:不转的话,由于精度问题,会导致计算异常复杂
27 | * 2. 绘制刻度:
28 | * - 根据中间指针位置的数值,来计算最小值位置与中间指针位置的距离
29 | * - 为了绘制性能,只绘制控件宽度范围内的刻度。但不出现数值突变(两侧刻度出现突然显示或不显示),两侧各增加2个单位
30 | * 3. 滑动时,通过移动最小位置与中间指针位置的距离,逆向推算当前刻度值
31 | * 4. 滑动停止后,自动调整到最近的刻度:使用滑动器Scroller,需要计算出最终要抵达的位置
32 | * 5. 惯性滑动:使用速度跟踪器VelocityTracker
33 | *
34 | * Author: Ralap
35 | * Description:
36 | * Date 2018/7/29
37 | */
38 | public class RuleView extends View {
39 | private static final boolean LOG_ENABLE = BuildConfig.DEBUG;
40 |
41 | /**
42 | * 滑动阈值
43 | */
44 | private final int TOUCH_SLOP;
45 | /**
46 | * 惯性滑动最小、最大速度
47 | */
48 | private final int MIN_FLING_VELOCITY;
49 | private final int MAX_FLING_VELOCITY;
50 |
51 | /**
52 | * 背景色
53 | */
54 | private int bgColor;
55 | /**
56 | * 刻度颜色
57 | */
58 | private int gradationColor;
59 | /**
60 | * 短刻度线宽度
61 | */
62 | private float shortLineWidth;
63 | /**
64 | * 长刻度线宽度
65 | * 默认 = 2 * shortLineWidth
66 | */
67 | private float longLineWidth ;
68 | /**
69 | * 短刻度长度
70 | */
71 | private float shortGradationLen;
72 | /**
73 | * 长刻度长度
74 | * 默认为短刻度的2倍
75 | */
76 | private float longGradationLen;
77 | /**
78 | * 刻度字体颜色
79 | */
80 | private int textColor;
81 | /**
82 | * 刻度字体大小
83 | */
84 | private float textSize;
85 | /**
86 | * 中间指针线颜色
87 | */
88 | private int indicatorLineColor;
89 | /**
90 | * 中间指针线宽度
91 | */
92 | private float indicatorLineWidth;
93 | /**
94 | * 中间指针线长度
95 | */
96 | private float indicatorLineLen;
97 | /**
98 | * 最小值
99 | */
100 | private float minValue;
101 | /**
102 | * 最大值
103 | */
104 | private float maxValue;
105 | /**
106 | * 当前值
107 | */
108 | private float currentValue;
109 | /**
110 | * 刻度最小单位
111 | */
112 | private float gradationUnit;
113 | /**
114 | * 需要绘制的数值
115 | */
116 | private int numberPerCount;
117 | /**
118 | * 刻度间距离
119 | */
120 | private float gradationGap;
121 | /**
122 | * 刻度与文字的间距
123 | */
124 | private float gradationNumberGap;
125 |
126 | /**
127 | * 最小数值,放大10倍:minValue * 10
128 | */
129 | private int mMinNumber;
130 | /**
131 | * 最大数值,放大10倍:maxValue * 10
132 | */
133 | private int mMaxNumber;
134 | /**
135 | * 当前数值
136 | */
137 | private int mCurrentNumber;
138 | /**
139 | * 最大数值与最小数值间的距离:(mMaxNumber - mMinNumber) / mNumberUnit * gradationGap
140 | */
141 | private float mNumberRangeDistance;
142 | /**
143 | * 刻度数值最小单位:gradationUnit * 10
144 | */
145 | private int mNumberUnit;
146 | /**
147 | * 当前数值与最小值的距离:(mCurrentNumber - minValue) / mNumberUnit * gradationGap
148 | */
149 | private float mCurrentDistance;
150 | /**
151 | * 控件宽度所占有的数值范围:mWidth / gradationGap * mNumberUnit
152 | */
153 | private int mWidthRangeNumber;
154 |
155 | /**
156 | * 普通画笔
157 | */
158 | private Paint mPaint;
159 | /**
160 | * 文字画笔
161 | */
162 | private TextPaint mTextPaint;
163 | /**
164 | * 滑动器
165 | */
166 | private Scroller mScroller;
167 | /**
168 | * 速度跟踪器
169 | */
170 | private VelocityTracker mVelocityTracker;
171 | /**
172 | * 尺寸
173 | */
174 | private int mWidth, mHalfWidth, mHeight;
175 |
176 | private int mDownX;
177 | private int mLastX, mLastY;
178 | private boolean isMoved;
179 |
180 | private OnValueChangedListener mValueChangedListener;
181 |
182 | /**
183 | * 当前值变化监听器
184 | */
185 | public interface OnValueChangedListener{
186 | void onValueChanged(float value);
187 | }
188 |
189 |
190 | public RuleView(Context context) {
191 | this(context, null);
192 | }
193 |
194 | public RuleView(Context context, @Nullable AttributeSet attrs) {
195 | this(context, attrs, 0);
196 | }
197 |
198 | public RuleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
199 | super(context, attrs, defStyleAttr);
200 | initAttrs(context, attrs);
201 |
202 | // 初始化final常量,必须在构造中赋初值
203 | ViewConfiguration viewConfiguration = ViewConfiguration.get(context);
204 | TOUCH_SLOP = viewConfiguration.getScaledTouchSlop();
205 | MIN_FLING_VELOCITY = viewConfiguration.getScaledMinimumFlingVelocity();
206 | MAX_FLING_VELOCITY = viewConfiguration.getScaledMaximumFlingVelocity();
207 |
208 | convertValue2Number();
209 | init(context);
210 | }
211 |
212 | private void initAttrs(Context context, AttributeSet attrs) {
213 | TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RuleView);
214 | bgColor = ta.getColor(R.styleable.RuleView_zjun_bgColor, Color.parseColor("#f5f8f5"));
215 | gradationColor = ta.getColor(R.styleable.RuleView_zjun_gradationColor, Color.LTGRAY);
216 | shortLineWidth = ta.getDimension(R.styleable.RuleView_gv_shortLineWidth, dp2px(1));
217 | shortGradationLen = ta.getDimension(R.styleable.RuleView_gv_shortGradationLen, dp2px(16));
218 | longGradationLen = ta.getDimension(R.styleable.RuleView_gv_longGradationLen, shortGradationLen * 2);
219 | longLineWidth = ta.getDimension(R.styleable.RuleView_gv_longLineWidth, shortLineWidth * 2);
220 | textColor = ta.getColor(R.styleable.RuleView_zjun_textColor, Color.BLACK);
221 | textSize = ta.getDimension(R.styleable.RuleView_zjun_textSize, sp2px(14));
222 | indicatorLineColor = ta.getColor(R.styleable.RuleView_zjun_indicatorLineColor, Color.parseColor("#48b975"));
223 | indicatorLineWidth = ta.getDimension(R.styleable.RuleView_zjun_indicatorLineWidth, dp2px(3f));
224 | indicatorLineLen = ta.getDimension(R.styleable.RuleView_gv_indicatorLineLen, dp2px(35f));
225 | minValue = ta.getFloat(R.styleable.RuleView_gv_minValue, 0f);
226 | maxValue = ta.getFloat(R.styleable.RuleView_gv_maxValue, 100f);
227 | currentValue = ta.getFloat(R.styleable.RuleView_gv_currentValue, 50f);
228 | gradationUnit = ta.getFloat(R.styleable.RuleView_gv_gradationUnit, .1f);
229 | numberPerCount = ta.getInt(R.styleable.RuleView_gv_numberPerCount, 10);
230 | gradationGap = ta.getDimension(R.styleable.RuleView_gv_gradationGap, dp2px(10));
231 | gradationNumberGap = ta.getDimension(R.styleable.RuleView_gv_gradationNumberGap, dp2px(8));
232 | ta.recycle();
233 | }
234 |
235 | /**
236 | * 初始化
237 | */
238 | private void init(Context context) {
239 | mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
240 | mPaint.setStrokeWidth(shortLineWidth);
241 |
242 | mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
243 | mTextPaint.setTextSize(textSize);
244 | mTextPaint.setColor(textColor);
245 |
246 | mScroller = new Scroller(context);
247 | }
248 |
249 | /**
250 | * 把真实数值转换成绘制数值
251 | * 为了防止float的精度丢失,把minValue、maxValue、currentValue、gradationUnit都放大10倍
252 | */
253 | private void convertValue2Number() {
254 | mMinNumber = (int) (minValue * 10);
255 | mMaxNumber = (int) (maxValue * 10);
256 | mCurrentNumber = (int) (currentValue * 10);
257 | mNumberUnit = (int) (gradationUnit * 10);
258 | mCurrentDistance = (mCurrentNumber - mMinNumber) / mNumberUnit * gradationGap;
259 | mNumberRangeDistance = (mMaxNumber - mMinNumber) / mNumberUnit * gradationGap;
260 | if (mWidth != 0) {
261 | // 初始化时,在onMeasure()里计算
262 | mWidthRangeNumber = (int) (mWidth / gradationGap * mNumberUnit);
263 | }
264 | }
265 |
266 |
267 | @Override
268 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
269 | mWidth = calculateSize(true, widthMeasureSpec);
270 | mHeight = calculateSize(false, heightMeasureSpec);
271 | mHalfWidth = mWidth >> 1;
272 | if (mWidthRangeNumber == 0) {
273 | mWidthRangeNumber = (int) (mWidth / gradationGap * mNumberUnit);
274 | }
275 | setMeasuredDimension(mWidth, mHeight);
276 | }
277 |
278 | /**
279 | * 计算宽度或高度的真实大小
280 | *
281 | * 宽或高为wrap_content时,父控件的测量模式无论是EXACTLY还是AT_MOST,默认给的测量模式都是AT_MOST,测量大小为父控件的size
282 | * 所以,我们宽度不管,只处理高度,默认80dp
283 | * @see ViewGroup#getChildMeasureSpec(int, int, int)
284 | *
285 | * @param isWidth 是不是宽度
286 | * @param spec 测量规则
287 | * @return 真实的大小
288 | */
289 | private int calculateSize(boolean isWidth, int spec) {
290 | final int mode = MeasureSpec.getMode(spec);
291 | final int size = MeasureSpec.getSize(spec);
292 |
293 | int realSize = size;
294 | switch (mode) {
295 | // 精确模式:已经确定具体数值:layout_width为具体值,或match_parent
296 | case MeasureSpec.EXACTLY:
297 | break;
298 | // 最大模式:最大不能超过父控件给的widthSize:layout_width为wrap_content
299 | case MeasureSpec.AT_MOST:
300 | if (!isWidth) {
301 | int defaultContentSize = dp2px(80);
302 | realSize = Math.min(realSize, defaultContentSize);
303 | }
304 | break;
305 | // 未指定尺寸模式:一般父控件是AdapterView
306 | case MeasureSpec.UNSPECIFIED:
307 | default:
308 |
309 | }
310 | logD("isWidth=%b, mode=%d, size=%d, realSize=%d", isWidth, mode, size, realSize);
311 | return realSize;
312 | }
313 |
314 |
315 | @Override
316 | public boolean onTouchEvent(MotionEvent event) {
317 | final int action = event.getAction();
318 | final int x = (int) event.getX();
319 | final int y = (int) event.getY();
320 | logD("onTouchEvent: action=%d", action);
321 | if (mVelocityTracker == null) {
322 | mVelocityTracker = VelocityTracker.obtain();
323 | }
324 | mVelocityTracker.addMovement(event);
325 | switch (action) {
326 | case MotionEvent.ACTION_DOWN:
327 | mScroller.forceFinished(true);
328 | mDownX = x;
329 | isMoved = false;
330 | break;
331 | case MotionEvent.ACTION_MOVE:
332 | final int dx = x - mLastX;
333 |
334 | // 判断是否已经滑动
335 | if (!isMoved) {
336 | final int dy = y - mLastY;
337 | // 滑动的触发条件:水平滑动大于垂直滑动;滑动距离大于阈值
338 | if (Math.abs(dx) < Math.abs(dy) || Math.abs(x - mDownX) < TOUCH_SLOP) {
339 | break;
340 | }
341 | isMoved = true;
342 | }
343 |
344 | mCurrentDistance += -dx;
345 | calculateValue();
346 | break;
347 | case MotionEvent.ACTION_UP:
348 | // 计算速度:使用1000ms为单位
349 | mVelocityTracker.computeCurrentVelocity(1000, MAX_FLING_VELOCITY);
350 | // 获取速度。速度有方向性,水平方向:左滑为负,右滑为正
351 | int xVelocity = (int) mVelocityTracker.getXVelocity();
352 | // 达到速度则惯性滑动,否则缓慢滑动到刻度
353 | if (Math.abs(xVelocity) >= MIN_FLING_VELOCITY) {
354 | // 速度具有方向性,需要取反
355 | mScroller.fling((int)mCurrentDistance, 0, -xVelocity, 0,
356 | 0, (int)mNumberRangeDistance, 0, 0);
357 | invalidate();
358 | } else {
359 | scrollToGradation();
360 | }
361 | break;
362 | default:
363 | break;
364 | }
365 | mLastX = x;
366 | mLastY = y;
367 | return true;
368 | }
369 |
370 | /**
371 | * 根据distance距离,计算数值
372 | */
373 | private void calculateValue() {
374 | // 限定范围:在最小值与最大值之间
375 | mCurrentDistance = Math.min(Math.max(mCurrentDistance, 0), mNumberRangeDistance);
376 | mCurrentNumber = mMinNumber + (int)(mCurrentDistance / gradationGap) * mNumberUnit;
377 | currentValue = mCurrentNumber / 10f;
378 | logD("calculateValue: mCurrentDistance=%f, mCurrentNumber=%d, currentValue=%f",
379 | mCurrentDistance, mCurrentNumber, currentValue);
380 | if (mValueChangedListener != null) {
381 | mValueChangedListener.onValueChanged(currentValue);
382 | }
383 | invalidate();
384 | }
385 |
386 | /**
387 | * 滑动到最近的刻度线上
388 | */
389 | private void scrollToGradation() {
390 | mCurrentNumber = mMinNumber + Math.round(mCurrentDistance / gradationGap) * mNumberUnit;
391 | mCurrentNumber = Math.min(Math.max(mCurrentNumber, mMinNumber), mMaxNumber);
392 | mCurrentDistance = (mCurrentNumber - mMinNumber) / mNumberUnit * gradationGap;
393 | currentValue = mCurrentNumber / 10f;
394 | logD("scrollToGradation: mCurrentDistance=%f, mCurrentNumber=%d, currentValue=%f",
395 | mCurrentDistance, mCurrentNumber, currentValue);
396 | if (mValueChangedListener != null) {
397 | mValueChangedListener.onValueChanged(currentValue);
398 | }
399 | invalidate();
400 | }
401 |
402 | @Override
403 | public void computeScroll() {
404 | if (mScroller.computeScrollOffset()) {
405 | if (mScroller.getCurrX() != mScroller.getFinalX()) {
406 | mCurrentDistance = mScroller.getCurrX();
407 | calculateValue();
408 | } else {
409 | scrollToGradation();
410 | }
411 | }
412 | }
413 |
414 | @Override
415 | protected void onDraw(Canvas canvas) {
416 | // 1 绘制背景色
417 | canvas.drawColor(bgColor);
418 | // 2 绘制刻度、数字
419 | drawGradation(canvas);
420 | // 3 绘制指针
421 | drawIndicator(canvas);
422 | }
423 |
424 | /**
425 | * 绘制刻度
426 | */
427 | private void drawGradation(Canvas canvas) {
428 | // 1 顶部基准线
429 | mPaint.setColor(gradationColor);
430 | mPaint.setStrokeWidth(shortLineWidth);
431 | canvas.drawLine(0, shortLineWidth * .5f, mWidth, 0, mPaint);
432 |
433 | /*
434 | 2 左侧刻度
435 | 2.1 计算左侧开始绘制的刻度
436 | */
437 | int startNum = ((int) mCurrentDistance - mHalfWidth) / (int) gradationGap * mNumberUnit + mMinNumber;
438 | // 扩展2个单位
439 | final int expendUnit = mNumberUnit << 1;
440 | // 左侧扩展
441 | startNum -= expendUnit;
442 | if (startNum < mMinNumber) {
443 | startNum = mMinNumber;
444 | }
445 | // 右侧扩展
446 | int rightMaxNum = (startNum + expendUnit) + mWidthRangeNumber + expendUnit;
447 | if (rightMaxNum > mMaxNumber) {
448 | rightMaxNum = mMaxNumber;
449 | }
450 | // 当前绘制刻度对应控件左侧的位置
451 | float distance = mHalfWidth - (mCurrentDistance - (startNum - mMinNumber) / mNumberUnit * gradationGap);
452 | final int perUnitCount = mNumberUnit * numberPerCount;
453 | logD("drawGradation: startNum=%d, rightNum=%d, perUnitCount=%d",
454 | startNum, rightMaxNum, perUnitCount);
455 | while (startNum <= rightMaxNum) {
456 | logD("drawGradation: startNum=%d", startNum);
457 | if (startNum % perUnitCount == 0) {
458 | // 长刻度:刻度宽度为短刻度的2倍
459 | mPaint.setStrokeWidth(longLineWidth);
460 | canvas.drawLine(distance, 0, distance, longGradationLen, mPaint);
461 |
462 | // 数值
463 | float fNum = startNum / 10f;
464 | String text = Float.toString(fNum);
465 | logD("drawGradation: text=%s", text);
466 | if (text.endsWith(".0")) {
467 | text = text.substring(0, text.length() - 2);
468 | }
469 | final float textWidth = mTextPaint.measureText(text);
470 | canvas.drawText(text, distance - textWidth * .5f, longGradationLen + gradationNumberGap + textSize, mTextPaint);
471 | } else {
472 | // 短刻度
473 | mPaint.setStrokeWidth(shortLineWidth);
474 | canvas.drawLine(distance, 0, distance, shortGradationLen, mPaint);
475 | }
476 | startNum += mNumberUnit;
477 | distance += gradationGap;
478 | }
479 | }
480 |
481 | /**
482 | * 绘制指针
483 | */
484 | private void drawIndicator(Canvas canvas) {
485 | mPaint.setColor(indicatorLineColor);
486 | mPaint.setStrokeWidth(indicatorLineWidth);
487 | // 圆头画笔
488 | mPaint.setStrokeCap(Paint.Cap.ROUND);
489 | //
490 | canvas.drawLine(mHalfWidth, 0, mHalfWidth, indicatorLineLen, mPaint);
491 | // 默认形状画笔
492 | mPaint.setStrokeCap(Paint.Cap.BUTT);
493 | }
494 |
495 | private int dp2px(float dp) {
496 | return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
497 | }
498 |
499 | private int sp2px(float sp) {
500 | return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, getResources().getDisplayMetrics());
501 | }
502 |
503 | @SuppressWarnings("all")
504 | private void logD(String format, Object... args) {
505 | if (LOG_ENABLE) {
506 | Log.d("GradationView", String.format("zjun@" + format, args));
507 | }
508 | }
509 |
510 | /**
511 | * 设置新值
512 | */
513 | public void setCurrentValue(float currentValue) {
514 | if (currentValue < minValue || currentValue > maxValue) {
515 | throw new IllegalArgumentException(String.format("The currentValue of %f is out of range: [%f, %f]",
516 | currentValue, minValue, maxValue));
517 | }
518 | if (!mScroller.isFinished()) {
519 | mScroller.forceFinished(true);
520 | }
521 | this.currentValue = currentValue;
522 | mCurrentNumber = (int) (this.currentValue * 10);
523 | final float newDistance = (mCurrentNumber - mMinNumber) / mNumberUnit * gradationGap;
524 | final int dx = (int) (newDistance - mCurrentDistance);
525 | // 最大2000ms
526 | final int duration = dx * 2000 / (int)mNumberRangeDistance;
527 | // 滑动到目标值
528 | mScroller.startScroll((int) mCurrentDistance, 0, dx, duration);
529 | postInvalidate();
530 | }
531 |
532 | public float getMinValue() {
533 | return minValue;
534 | }
535 |
536 | public float getMaxValue() {
537 | return maxValue;
538 | }
539 |
540 | /**
541 | * 获取当前值
542 | */
543 | public float getCurrentValue() {
544 | return this.currentValue;
545 | }
546 |
547 | /**
548 | * 重新配置参数
549 | *
550 | * @param minValue 最小值
551 | * @param maxValue 最大值
552 | * @param curValue 当前值
553 | * @param unit 最小单位所代表的值
554 | * @param perCount 相邻两条长刻度线之间被分成的隔数量
555 | */
556 | public void setValue(float minValue, float maxValue, float curValue, float unit, int perCount) {
557 | if (minValue > maxValue || curValue < minValue || curValue > maxValue) {
558 | throw new IllegalArgumentException(String.format("The given values are invalid, check firstly: " +
559 | "minValue=%f, maxValue=%f, curValue=%s", minValue, maxValue, curValue));
560 | }
561 | if (!mScroller.isFinished()) {
562 | mScroller.forceFinished(true);
563 | }
564 | this.minValue = minValue;
565 | this.maxValue = maxValue;
566 | this.currentValue = curValue;
567 | this.gradationUnit = unit;
568 | this.numberPerCount = perCount;
569 | convertValue2Number();
570 | if (mValueChangedListener != null) {
571 | mValueChangedListener.onValueChanged(currentValue);
572 | }
573 | postInvalidate();
574 | }
575 |
576 | public void setOnValueChangedListener(OnValueChangedListener listener) {
577 | this.mValueChangedListener = listener;
578 | }
579 | }
580 |
--------------------------------------------------------------------------------
/rule-view/src/main/java/com/zjun/widget/TimeRuleView.java:
--------------------------------------------------------------------------------
1 | package com.zjun.widget;
2 |
3 | import android.content.Context;
4 | import android.content.res.TypedArray;
5 | import android.graphics.Canvas;
6 | import android.graphics.Color;
7 | import android.graphics.Paint;
8 | import android.graphics.Path;
9 | import android.support.annotation.IntRange;
10 | import android.support.annotation.Nullable;
11 | import android.text.TextPaint;
12 | import android.util.AttributeSet;
13 | import android.util.Log;
14 | import android.util.TypedValue;
15 | import android.view.MotionEvent;
16 | import android.view.ScaleGestureDetector;
17 | import android.view.VelocityTracker;
18 | import android.view.View;
19 | import android.view.ViewConfiguration;
20 | import android.widget.Scroller;
21 |
22 | import java.lang.reflect.Field;
23 | import java.util.List;
24 |
25 | /**
26 | * TimeRuleView
27 | *
28 | * 时间尺控件
29 | * (仿“萤石云视频”里的时间选择控件)
30 | *
31 | * 功能:
32 | * - 可选择一天(00:00 ~ 24:00)内的任一时刻,精确到秒级
33 | * - 可显示多个时间块
34 | * - 支持滑动及惯性滑动
35 | * - 支持缩放时间间隔
36 | * - 支持滑动与缩放的连续切换
37 | *
38 | * 思路:
39 | * - 时间绘制思路参考{@link RuleView}
40 | * - 时间缩放,采用缩放手势检测器 ScaleGestureDetector
41 | * - 缩放的等级估算方式:进入默认比例为1,根据每隔所占的秒数与宽度,可估算出每个等级的宽度范围,再与默认等级对应的宽度相除,即可算出缩放比例
42 | * - 惯性滑动,使用速度追踪器 VelocityTracker
43 | * - 缩放与滑动之间的连续操作,ScaleGestureDetector 开始与结束的条件是第二个手指按下与松开,
44 | * 所以onTouchEvent()中应该使用 getActionMasked()来监听第二个手指的 DOWN(ACTION_POINTER_DOWN) 与 UP(ACTION_POINTER_UP) 事件,
45 | * MOVE 都是一样的
46 | * - 时间块,由起始时间与终止时间组成,采用一个有序的集合来装入即可
47 | *
48 | * Author: Ralap
49 | * Description:
50 | * Date 2018/8/11
51 | */
52 | public class TimeRuleView extends View {
53 |
54 | private static final boolean LOG_ENABLE = BuildConfig.DEBUG;
55 | public static final int MAX_TIME_VALUE = 24 * 3600;
56 |
57 | private int bgColor;
58 | /**
59 | * 刻度颜色
60 | */
61 | private int gradationColor;
62 | /**
63 | * 时间块的高度
64 | */
65 | private float partHeight;
66 | /**
67 | * 时间块的颜色
68 | */
69 | private int partColor;
70 | /**
71 | * 刻度宽度
72 | */
73 | private float gradationWidth;
74 | /**
75 | * 秒、分、时刻度的长度
76 | */
77 | private float secondLen;
78 | private float minuteLen;
79 | private float hourLen;
80 | /**
81 | * 刻度数值颜色、大小、与时刻度的距离
82 | */
83 | private int gradationTextColor;
84 | private float gradationTextSize;
85 | private float gradationTextGap;
86 |
87 | /**
88 | * 当前时间,单位:s
89 | */
90 | private @IntRange(from = 0, to = MAX_TIME_VALUE) int currentTime;
91 | /**
92 | * 指针颜色
93 | */
94 | private int indicatorColor;
95 | /**
96 | * 指针上三角形的边长
97 | */
98 | private float indicatorTriangleSideLen;
99 | /**
100 | * 指针的宽度
101 | */
102 | private float indicatorWidth;
103 |
104 | /**
105 | * 最小单位对应的单位秒数值,一共四级: 10s、1min、5min、15min
106 | * 与 {@link #mPerTextCounts} 和 {@link #mPerCountScaleThresholds} 对应的索引值
107 | *
108 | * 可以组合优化成数组
109 | */
110 | private static int[] mUnitSeconds = {
111 | 10, 10, 10, 10,
112 | 60, 60,
113 | 5*60, 5*60,
114 | 15 * 60, 15 * 60, 15 * 60, 15 * 60, 15 * 60, 15 * 60
115 | };
116 |
117 | /**
118 | * 数值显示间隔。一共13级,第一级最大值,不包括
119 | */
120 | @SuppressWarnings("all")
121 | private static int[] mPerTextCounts = {
122 | 60, 60, 2 * 60, 4 * 60, // 10s/unit: 最大值, 1min, 2min, 4min
123 | 5 * 60, 10 * 60, // 1min/unit: 5min, 10min
124 | 20 * 60, 30 * 60, // 5min/unit: 20min, 30min
125 | 3600, 2 * 3600, 3 * 3600, 4 * 3600, 5 * 3600, 6 * 3600 // 15min/unit
126 | };
127 |
128 | /**
129 | * 与 {@link #mPerTextCounts} 对应的阈值,在此阈值与前一个阈值之间,则使用此阈值对应的间隔数值
130 | * 如:1.5f 代表 4*60 对应的阈值,如果 mScale >= 1.5f && mScale < 1.8f,则使用 4*60
131 | *
132 | * 这些数值,都是估算出来的
133 | */
134 | @SuppressWarnings("all")
135 | private float[] mPerCountScaleThresholds = {
136 | 6f, 3.6f, 1.8f, 1.5f, // 10s/unit: 最大值, 1min, 2min, 4min
137 | 0.8f, 0.4f, // 1min/unit: 5min, 10min
138 | 0.25f, 0.125f, // 5min/unit: 20min, 30min
139 | 0.07f, 0.04f, 0.03f, 0.025f, 0.02f, 0.015f // 15min/unit: 1h, 2h, 3h, 4h, 5h, 6h
140 | };
141 | /**
142 | * 默认mScale为1
143 | */
144 | private float mScale = 1;
145 | /**
146 | * 1s对应的间隔,比较好估算
147 | */
148 | private final float mOneSecondGap = dp2px(12) / 60f;
149 | /**
150 | * 当前最小单位秒数值对应的间隔
151 | */
152 | private float mUnitGap = mOneSecondGap * 60;
153 | /**
154 | * 默认索引值
155 | */
156 | private int mPerTextCountIndex = 4;
157 | /**
158 | * 一格代表的秒数。默认1min
159 | */
160 | private int mUnitSecond = mUnitSeconds[mPerTextCountIndex];
161 |
162 | /**
163 | * 数值文字宽度的一半:时间格式为“00:00”,所以长度固定
164 | */
165 | private final float mTextHalfWidth;
166 |
167 | private final int SCROLL_SLOP;
168 | private final int MIN_VELOCITY;
169 | private final int MAX_VELOCITY;
170 |
171 | /**
172 | * 当前时间与 00:00 的距离值
173 | */
174 | private float mCurrentDistance;
175 |
176 |
177 | private Paint mPaint;
178 | private TextPaint mTextPaint;
179 | private Path mTrianglePath;
180 | private Scroller mScroller;
181 | private VelocityTracker mVelocityTracker;
182 |
183 | /**
184 | * 缩放手势检测器
185 | */
186 | private ScaleGestureDetector mScaleGestureDetector;
187 |
188 | private int mWidth, mHeight;
189 | private int mHalfWidth;
190 |
191 | private int mInitialX;
192 | private int mLastX, mLastY;
193 | private boolean isMoving;
194 | private boolean isScaling;
195 |
196 | private List mTimePartList;
197 | private OnTimeChangedListener mListener;
198 |
199 | public interface OnTimeChangedListener{
200 | void onTimeChanged(int newTimeValue);
201 | }
202 |
203 | /**
204 | * 时间片段
205 | */
206 | public static class TimePart{
207 | /**
208 | * 起始时间,单位:s,取值范围∈[0, 86399]
209 | * 0 —— 00:00:00
210 | * 86399 —— 23:59:59
211 | */
212 | public int startTime;
213 |
214 | /**
215 | * 结束时间,必须大于{@link #startTime}
216 | */
217 | public int endTime;
218 | }
219 |
220 | public TimeRuleView(Context context) {
221 | this(context, null);
222 | }
223 |
224 | public TimeRuleView(Context context, @Nullable AttributeSet attrs) {
225 | this(context, attrs, 0);
226 | }
227 |
228 | public TimeRuleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
229 | super(context, attrs, defStyleAttr);
230 | initAttrs(context, attrs);
231 |
232 | init(context);
233 | initScaleGestureDetector(context);
234 |
235 | mTextHalfWidth = mTextPaint.measureText("00:00") * .5f;
236 | ViewConfiguration viewConfiguration = ViewConfiguration.get(context);
237 | SCROLL_SLOP = viewConfiguration.getScaledTouchSlop();
238 | MIN_VELOCITY = viewConfiguration.getScaledMinimumFlingVelocity();
239 | MAX_VELOCITY = viewConfiguration.getScaledMaximumFlingVelocity();
240 |
241 | calculateValues();
242 | }
243 |
244 | private void initAttrs(Context context, AttributeSet attrs) {
245 | TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TimeRuleView);
246 | bgColor = ta.getColor(R.styleable.TimeRuleView_zjun_bgColor, Color.parseColor("#EEEEEE"));
247 | gradationColor = ta.getColor(R.styleable.TimeRuleView_zjun_gradationColor, Color.GRAY);
248 | partHeight = ta.getDimension(R.styleable.TimeRuleView_trv_partHeight, dp2px(20));
249 | partColor = ta.getColor(R.styleable.TimeRuleView_trv_partColor, Color.parseColor("#F58D24"));
250 | gradationWidth = ta.getDimension(R.styleable.TimeRuleView_trv_gradationWidth, 1);
251 | secondLen = ta.getDimension(R.styleable.TimeRuleView_trv_secondLen, dp2px(3));
252 | minuteLen = ta.getDimension(R.styleable.TimeRuleView_trv_minuteLen, dp2px(5));
253 | hourLen = ta.getDimension(R.styleable.TimeRuleView_trv_hourLen, dp2px(10));
254 | gradationTextColor = ta.getColor(R.styleable.TimeRuleView_trv_gradationTextColor, Color.GRAY);
255 | gradationTextSize = ta.getDimension(R.styleable.TimeRuleView_trv_gradationTextSize, sp2px(12));
256 | gradationTextGap = ta.getDimension(R.styleable.TimeRuleView_trv_gradationTextGap, dp2px(2));
257 | currentTime = ta.getInt(R.styleable.TimeRuleView_trv_currentTime, 0);
258 | indicatorTriangleSideLen = ta.getDimension(R.styleable.TimeRuleView_trv_indicatorTriangleSideLen, dp2px(15));
259 | indicatorWidth = ta.getDimension(R.styleable.TimeRuleView_zjun_indicatorLineWidth, dp2px(1));
260 | indicatorColor = ta.getColor(R.styleable.TimeRuleView_zjun_indicatorLineColor, Color.RED);
261 | ta.recycle();
262 | }
263 |
264 | private void calculateValues() {
265 | mCurrentDistance = currentTime / mUnitSecond * mUnitGap;
266 | }
267 |
268 | private void init(Context context) {
269 | mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
270 |
271 | mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
272 | mTextPaint.setTextSize(gradationTextSize);
273 | mTextPaint.setColor(gradationTextColor);
274 |
275 | mTrianglePath = new Path();
276 |
277 | mScroller = new Scroller(context);
278 | }
279 |
280 | private void initScaleGestureDetector(Context context) {
281 | mScaleGestureDetector = new ScaleGestureDetector(context, new ScaleGestureDetector.OnScaleGestureListener() {
282 |
283 | /**
284 | * 缩放被触发(会调用0次或者多次),
285 | * 如果返回 true 则表示当前缩放事件已经被处理,检测器会重新积累缩放因子
286 | * 返回 false 则会继续积累缩放因子。
287 | */
288 | @Override
289 | public boolean onScale(ScaleGestureDetector detector) {
290 | final float scaleFactor = detector.getScaleFactor();
291 | logD("onScale...focusX=%f, focusY=%f, scaleFactor=%f",
292 | detector.getFocusX(), detector.getFocusY(), scaleFactor);
293 |
294 | final float maxScale = mPerCountScaleThresholds[0];
295 | final float minScale = mPerCountScaleThresholds[mPerCountScaleThresholds.length - 1];
296 | if (scaleFactor > 1 && mScale >= maxScale) {
297 | // 已经放大到最大值
298 | return true;
299 | } else if (scaleFactor < 1 && mScale <= minScale) {
300 | // 已经缩小到最小值
301 | return true;
302 | }
303 |
304 | mScale *= scaleFactor;
305 | mScale = Math.max(minScale, Math.min(maxScale, mScale));
306 | mPerTextCountIndex = findScaleIndex(mScale);
307 |
308 | mUnitSecond = mUnitSeconds[mPerTextCountIndex];
309 | mUnitGap = mScale * mOneSecondGap * mUnitSecond;
310 | logD("onScale: mScale=%f, mPerTextCountIndex=%d, mUnitSecond=%d, mUnitGap=%f",
311 | mScale, mPerTextCountIndex, mUnitSecond, mUnitGap);
312 |
313 | mCurrentDistance = (float) currentTime / mUnitSecond * mUnitGap;
314 | invalidate();
315 | return true;
316 | }
317 |
318 | @Override
319 | public boolean onScaleBegin(ScaleGestureDetector detector) {
320 | logD("onScaleBegin...");
321 | isScaling = true;
322 | return true;
323 | }
324 |
325 | @Override
326 | public void onScaleEnd(ScaleGestureDetector detector) {
327 | isScaling = false;
328 | logD("onScaleEnd...");
329 | }
330 | });
331 |
332 | // 调整最小跨度值。默认值27mm(>=sw600dp的32mm),太大了,效果不好
333 | Class clazz = ScaleGestureDetector.class;
334 | int newMinSpan = ViewConfiguration.get(context).getScaledTouchSlop();
335 | try {
336 | Field mMinSpanField = clazz.getDeclaredField("mMinSpan");
337 | mMinSpanField.setAccessible(true);
338 | mMinSpanField.set(mScaleGestureDetector, newMinSpan);
339 | mMinSpanField.setAccessible(false);
340 | } catch (NoSuchFieldException e) {
341 | e.printStackTrace();
342 | } catch (IllegalAccessException e) {
343 | e.printStackTrace();
344 | }
345 | }
346 |
347 | /**
348 | * 二分法查找缩放值对应的索引值
349 | */
350 | private int findScaleIndex(float scale) {
351 | final int size = mPerCountScaleThresholds.length;
352 | int min = 0;
353 | int max = size - 1;
354 | int mid = (min + max) >> 1;
355 | while (!(scale >= mPerCountScaleThresholds[mid] && scale < mPerCountScaleThresholds[mid - 1])) {
356 | if (scale >= mPerCountScaleThresholds[mid - 1]) {
357 | // 因为值往小区,index往大取,所以不能为mid -1
358 | max = mid;
359 | } else {
360 | min = mid + 1;
361 | }
362 | mid = (min + max) >> 1;
363 | if (min >= max) {
364 | break;
365 | }
366 | if (mid == 0) {
367 | break;
368 | }
369 | }
370 | return mid;
371 | }
372 |
373 |
374 | @Override
375 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
376 | mWidth = MeasureSpec.getSize(widthMeasureSpec);
377 | mHeight = MeasureSpec.getSize(heightMeasureSpec);
378 |
379 | // 只处理wrap_content的高度,设置为80dp
380 | if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) {
381 | mHeight = dp2px(60);
382 | }
383 | mHalfWidth = mWidth >> 1;
384 |
385 | setMeasuredDimension(mWidth, mHeight);
386 | }
387 |
388 | @Override
389 | public boolean onTouchEvent(MotionEvent event) {
390 | final int actionIndex = event.getActionIndex();
391 | int pointerId = event.getPointerId(actionIndex);
392 | final int actionMasked = event.getActionMasked();
393 | final int action = event.getAction();
394 | final int pointerCount = event.getPointerCount();
395 | logD("onTouchEvent: isScaling=%b, actionIndex=%d, pointerId=%d, actionMasked=%d, action=%d, pointerCount=%d",
396 | isScaling, actionIndex, pointerId, actionMasked, action, pointerCount);
397 | final int x = (int) event.getX();
398 | final int y = (int) event.getY();
399 | mScaleGestureDetector.onTouchEvent(event);
400 |
401 | if (mVelocityTracker == null) {
402 | mVelocityTracker = VelocityTracker.obtain();
403 | }
404 | mVelocityTracker.addMovement(event);
405 | switch (actionMasked) {
406 | case MotionEvent.ACTION_DOWN:
407 | isMoving = false;
408 | mInitialX = x;
409 | if (!mScroller.isFinished()) {
410 | mScroller.forceFinished(true);
411 | }
412 | break;
413 | case MotionEvent.ACTION_POINTER_DOWN:
414 | // 只要第二手指按下,就禁止滑动
415 | isScaling = true;
416 | isMoving = false;
417 | break;
418 | case MotionEvent.ACTION_MOVE:
419 | if (isScaling) {
420 | break;
421 | }
422 | int dx = x - mLastX;
423 | if (!isMoving) {
424 | final int dy = y - mLastY;
425 | if (Math.abs(x - mInitialX) <= SCROLL_SLOP || Math.abs(dx) <= Math.abs(dy)) {
426 | break;
427 | }
428 | isMoving = true;
429 | }
430 | mCurrentDistance -= dx;
431 | computeTime();
432 | break;
433 | case MotionEvent.ACTION_UP:
434 | if (isScaling || !isMoving) {
435 | break;
436 | }
437 | mVelocityTracker.computeCurrentVelocity(1000, MAX_VELOCITY);
438 | final int xVelocity = (int) mVelocityTracker.getXVelocity();
439 | if (Math.abs(xVelocity) >= MIN_VELOCITY) {
440 | // 惯性滑动
441 | final int maxDistance = (int) (MAX_TIME_VALUE / mUnitGap * mUnitGap);
442 | mScroller.fling((int) mCurrentDistance, 0, -xVelocity, 0, 0, maxDistance, 0, 0);
443 | invalidate();
444 | }
445 | break;
446 | case MotionEvent.ACTION_POINTER_UP:
447 | // 两个中的有一个手指被抬起,允许滑动。同时把未抬起的手机当前位置赋给初始X
448 | isScaling = false;
449 | int restIndex = actionIndex == 0 ? 1 : 0;
450 | mInitialX = (int) event.getX(restIndex);
451 | break;
452 | default: break;
453 | }
454 | mLastX = x;
455 | mLastY = y;
456 | return true;
457 | }
458 |
459 | private void computeTime() {
460 | // 不用转float,肯定能整除
461 | float maxDistance = MAX_TIME_VALUE / mUnitSecond * mUnitGap;
462 | // 限定范围
463 | mCurrentDistance = Math.min(maxDistance, Math.max(0, mCurrentDistance));
464 | currentTime = (int) (mCurrentDistance / mUnitGap * mUnitSecond);
465 | if (mListener != null) {
466 | mListener.onTimeChanged(currentTime);
467 | }
468 | invalidate();
469 | }
470 |
471 | @Override
472 | protected void onDraw(Canvas canvas) {
473 | // 背景
474 | canvas.drawColor(bgColor);
475 |
476 | // 刻度
477 | drawRule(canvas);
478 |
479 | // 时间段
480 | drawTimeParts(canvas);
481 |
482 | // 当前时间指针
483 | drawTimeIndicator(canvas);
484 | }
485 |
486 | @Override
487 | public void computeScroll() {
488 | if (mScroller.computeScrollOffset()) {
489 | mCurrentDistance = mScroller.getCurrX();
490 | computeTime();
491 | }
492 | }
493 |
494 | /**
495 | * 绘制刻度
496 | */
497 | private void drawRule(Canvas canvas) {
498 | // 移动画布坐标系
499 | canvas.save();
500 | canvas.translate(0, partHeight);
501 | mPaint.setColor(gradationColor);
502 | mPaint.setStrokeWidth(gradationWidth);
503 |
504 | // 刻度
505 | int start = 0;
506 | float offset = mHalfWidth - mCurrentDistance;
507 | final int perTextCount = mPerTextCounts[mPerTextCountIndex];
508 | while (start <= MAX_TIME_VALUE) {
509 | // 刻度
510 | if (start % 3600 == 0) {
511 | // 时刻度
512 | canvas.drawLine(offset, 0, offset, hourLen, mPaint);
513 | } else if (start % 60 == 0) {
514 | // 分刻度
515 | canvas.drawLine(offset, 0, offset, minuteLen, mPaint);
516 | } else{
517 | // 秒刻度
518 | canvas.drawLine(offset, 0, offset, secondLen, mPaint);
519 | }
520 |
521 | // 时间数值
522 | if (start % perTextCount == 0) {
523 | String text = formatTimeHHmm(start);
524 | canvas.drawText(text, offset - mTextHalfWidth, hourLen + gradationTextGap + gradationTextSize, mTextPaint);
525 | }
526 |
527 | start += mUnitSecond;
528 | offset += mUnitGap;
529 | }
530 | canvas.restore();
531 | }
532 |
533 | /**
534 | * 绘制当前时间指针
535 | */
536 | private void drawTimeIndicator(Canvas canvas) {
537 | // 指针
538 | mPaint.setColor(indicatorColor);
539 | mPaint.setStrokeWidth(indicatorWidth);
540 | canvas.drawLine(mHalfWidth, 0, mHalfWidth, mHeight, mPaint);
541 |
542 | // 正三角形
543 | if (mTrianglePath.isEmpty()) {
544 | //
545 | final float halfSideLen = indicatorTriangleSideLen * .5f;
546 | mTrianglePath.moveTo(mHalfWidth - halfSideLen, 0);
547 | mTrianglePath.rLineTo(indicatorTriangleSideLen, 0);
548 | mTrianglePath.rLineTo(-halfSideLen, (float) (Math.sin(Math.toRadians(60)) * halfSideLen));
549 | mTrianglePath.close();
550 | }
551 | mPaint.setStrokeWidth(1);
552 | mPaint.setStyle(Paint.Style.FILL);
553 | canvas.drawPath(mTrianglePath, mPaint);
554 | mPaint.setStyle(Paint.Style.STROKE);
555 | }
556 |
557 | /**
558 | * 绘制时间段
559 | */
560 | private void drawTimeParts(Canvas canvas) {
561 | if (mTimePartList == null) {
562 | return;
563 | }
564 | // 不用矩形,直接使用直线绘制
565 | mPaint.setStrokeWidth(partHeight);
566 | mPaint.setColor(partColor);
567 | float start, end;
568 | final float halfPartHeight = partHeight * .5f;
569 | final float secondGap = mUnitGap / mUnitSecond;
570 | for (int i = 0, size = mTimePartList.size(); i < size; i++) {
571 | TimePart timePart = mTimePartList.get(i);
572 | start = mHalfWidth - mCurrentDistance + timePart.startTime * secondGap;
573 | end = mHalfWidth - mCurrentDistance + timePart.endTime * secondGap;
574 | canvas.drawLine(start, halfPartHeight, end, halfPartHeight, mPaint);
575 | }
576 | }
577 |
578 | /**
579 | * 格式化时间 HH:mm
580 | * @param timeValue 具体时间值
581 | * @return 格式化后的字符串,eg:3600 to 01:00
582 | */
583 | public static String formatTimeHHmm(@IntRange(from = 0, to = MAX_TIME_VALUE) int timeValue) {
584 | if (timeValue < 0){
585 | timeValue=0;
586 | }
587 | int hour = timeValue / 3600;
588 | int minute = timeValue % 3600 / 60;
589 | StringBuilder sb = new StringBuilder();
590 | if (hour < 10) {
591 | sb.append('0');
592 | }
593 | sb.append(hour).append(':');
594 | if (minute < 10) {
595 | sb.append('0');
596 | }
597 | sb.append(minute);
598 | return sb.toString();
599 | }
600 |
601 | /**
602 | * 格式化时间 HH:mm:ss
603 | * @param timeValue 具体时间值
604 | * @return 格式化后的字符串,eg:3600 to 01:00:00
605 | */
606 | public static String formatTimeHHmmss(@IntRange(from = 0, to = MAX_TIME_VALUE) int timeValue) {
607 | int hour = timeValue / 3600;
608 | int minute = timeValue % 3600 / 60;
609 | int second = timeValue % 3600 % 60;
610 | StringBuilder sb = new StringBuilder();
611 |
612 | if (hour < 10) {
613 | sb.append('0');
614 | }
615 | sb.append(hour).append(':');
616 |
617 | if (minute < 10) {
618 | sb.append('0');
619 | }
620 | sb.append(minute);
621 | sb.append(':');
622 |
623 | if (second < 10) {
624 | sb.append('0');
625 | }
626 | sb.append(second);
627 | return sb.toString();
628 | }
629 |
630 | private int dp2px(float dp) {
631 | return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
632 | }
633 |
634 | private int sp2px(float sp) {
635 | return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, getResources().getDisplayMetrics());
636 | }
637 |
638 | @SuppressWarnings("all")
639 | private void logD(String format, Object... args) {
640 | if (LOG_ENABLE) {
641 | Log.d("MoneySelectRuleView", String.format("zjun@" + format, args));
642 | }
643 | }
644 |
645 | /**
646 | * 设置时间变化监听事件
647 | * @param listener 监听回调
648 | */
649 | public void setOnTimeChangedListener(OnTimeChangedListener listener) {
650 | this.mListener = listener;
651 | }
652 |
653 | /**
654 | * 设置时间块(段)集合
655 | * @param timePartList 时间块集合
656 | */
657 | public void setTimePartList(List timePartList) {
658 | this.mTimePartList = timePartList;
659 | postInvalidate();
660 | }
661 |
662 | /**
663 | * 设置当前时间
664 | * @param currentTime 当前时间
665 | */
666 | public void setCurrentTime(@IntRange(from = 0, to = MAX_TIME_VALUE) int currentTime) {
667 | this.currentTime = currentTime;
668 | calculateValues();
669 | postInvalidate();
670 | }
671 |
672 | }
673 |
--------------------------------------------------------------------------------
/rule-view/src/main/res/values/attrs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
--------------------------------------------------------------------------------
/rule-view/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | gradation-view
3 | 剩余金额
4 |
5 | #eb4c1c
6 |
7 |
--------------------------------------------------------------------------------
/rule-view/src/test/java/com/zjun/widget/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.zjun.widget;
2 |
3 | import org.junit.Test;
4 |
5 | import java.text.NumberFormat;
6 |
7 | import static org.junit.Assert.*;
8 |
9 | /**
10 | * Example local unit test, which will execute on the development machine (host).
11 | *
12 | * @see Testing documentation
13 | */
14 | public class ExampleUnitTest {
15 | @Test
16 | public void addition_isCorrect() {
17 | assertEquals(4, 2 + 2);
18 | }
19 |
20 | @Test
21 | public void test() {
22 | float[] nums = {
23 | 3.005821f,
24 | 1f,
25 | 0.56f,
26 | 0.3f,
27 | 0.9f,
28 | 1.5f,
29 | 1.7f,
30 | 2.0f,
31 | 5f,
32 | 0.0001f,
33 | };
34 |
35 | for (float num : nums) {
36 | println("%f =%d", findScaleIndex(num));
37 | }
38 | }
39 |
40 | private float[] mPerCountScaleThresholds = {
41 | 6f, 3.6f, 1.8f, 1.5f, // 10s/unit: 最大值, 1min, 2min, 4min
42 | 0.8f, 0.4f, // 1min/unit: 5min, 10min
43 | 0.25f, 0.125f, // 5min/unit: 20min, 30min
44 | 0.07f, 0.04f, 0.03f, 0.025f, 0.02f, 0.015f // 15min/unit: 1h, 2h, 3h, 4h, 5h, 6h
45 | };
46 |
47 | private int findScaleIndex(float scale) {
48 | final int size = mPerCountScaleThresholds.length;
49 | int min = 0;
50 | int max = size - 1;
51 | int mid = (min + max) >> 1;
52 | while (!(scale >= mPerCountScaleThresholds[mid] && scale < mPerCountScaleThresholds[mid - 1])) {
53 | if (scale >= mPerCountScaleThresholds[mid - 1]) {
54 | // 因为值往小区,index往大取,所以不能为mid -1
55 | max = mid;
56 | } else {
57 | min = mid + 1;
58 | }
59 | mid = (min + max) >> 1;
60 | if (min >= max) {
61 | break;
62 | }
63 | if (mid == 0) {
64 | break;
65 | }
66 | }
67 | return mid;
68 | }
69 |
70 | private void println(String format, Object... args) {
71 | System.out.println(String.format(format, args));
72 | }
73 | }
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':rule-view'
2 |
--------------------------------------------------------------------------------