characterIndicesMap,
66 | TickerDrawMetrics metrics) {
67 | this.characterList = characterList;
68 | this.characterIndicesMap = characterIndicesMap;
69 | this.metrics = metrics;
70 | }
71 |
72 | /**
73 | * Tells the column that the next character it should show is {@param targetChar}. This can
74 | * change can either be animated or instant depending on the animation progress set by
75 | * {@link #setAnimationProgress(float)}.
76 | */
77 | void setTargetChar(char targetChar) {
78 | // Set the current and target characters for the animation
79 | this.targetChar = targetChar;
80 | this.sourceWidth = this.currentWidth;
81 | this.targetWidth = metrics.getCharWidth(targetChar);
82 | this.minimumRequiredWidth = Math.max(this.sourceWidth, this.targetWidth);
83 |
84 | // Calculate the current indices
85 | setCharacterIndices();
86 |
87 | final boolean scrollDown = endIndex >= startIndex;
88 | directionAdjustment = scrollDown ? 1 : -1;
89 |
90 | // Save the currentBottomDelta as previousBottomDelta in case this call to setTargetChar
91 | // interrupted a previously running animation. The deltas will then be used to compute
92 | // offset so that the interruption feels smooth on the UI.
93 | previousBottomDelta = currentBottomDelta;
94 | currentBottomDelta = 0f;
95 | }
96 |
97 | char getCurrentChar() {
98 | return currentChar;
99 | }
100 |
101 | char getTargetChar() {
102 | return targetChar;
103 | }
104 |
105 | float getCurrentWidth() {
106 | return currentWidth;
107 | }
108 |
109 | float getMinimumRequiredWidth() {
110 | return minimumRequiredWidth;
111 | }
112 |
113 | /**
114 | * A helper method for populating {@link #startIndex} and {@link #endIndex} given the
115 | * current and target characters for the animation.
116 | */
117 | private void setCharacterIndices() {
118 | startIndex = characterIndicesMap.containsKey(currentChar)
119 | ? characterIndicesMap.get(currentChar) : UNKNOWN_START_INDEX;
120 | endIndex = characterIndicesMap.containsKey(targetChar)
121 | ? characterIndicesMap.get(targetChar) : UNKNOWN_END_INDEX;
122 | }
123 |
124 | void onAnimationEnd() {
125 | minimumRequiredWidth = currentWidth;
126 | }
127 |
128 | void setAnimationProgress(float animationProgress) {
129 | if (animationProgress == 1f) {
130 | // Animation finished (or never started), set to stable state.
131 | this.currentChar = this.targetChar;
132 | currentBottomDelta = 0f;
133 | previousBottomDelta = 0f;
134 | }
135 |
136 | final float charHeight = metrics.getCharHeight();
137 |
138 | // First let's find the total height of this column between the start and end chars.
139 | final float totalHeight = charHeight * Math.abs(endIndex - startIndex);
140 |
141 | // The current base is then the part of the total height that we have progressed to
142 | // from the animation. For example, there might be 5 characters, each character is
143 | // 2px tall, so the totalHeight is 10. If we are at 50% progress, then our baseline
144 | // in this column is at 5 out of 10 (which is the 3rd character with a -50% offset
145 | // to the baseline).
146 | final float currentBase = animationProgress * totalHeight;
147 |
148 | // Given the current base, we now can find which character should drawn on the bottom.
149 | // Note that this position is a float. For example, if the bottomCharPosition is
150 | // 4.5, it means that the bottom character is the 4th character, and it has a -50%
151 | // offset relative to the baseline.
152 | final float bottomCharPosition = currentBase / charHeight;
153 |
154 | // By subtracting away the integer part of bottomCharPosition, we now have the
155 | // percentage representation of the bottom char's offset.
156 | final float bottomCharOffsetPercentage = bottomCharPosition - (int) bottomCharPosition;
157 |
158 | // We might have interrupted a previous animation if previousBottomDelta is not 0f.
159 | // If that's the case, we need to take this delta into account so that the previous
160 | // character offset won't be wiped away when we start a new animation.
161 | // We multiply by the inverse percentage so that the offset contribution from the delta
162 | // progresses along with the rest of the animation (from full delta to 0).
163 | final float additionalDelta = previousBottomDelta * (1f - animationProgress);
164 |
165 | // Now, using the bottom char's offset percentage and the delta we have from the
166 | // previous animation, we can now compute what's the actual offset of the bottom
167 | // character in the column relative to the baseline.
168 | bottomDelta = bottomCharOffsetPercentage * charHeight * directionAdjustment
169 | + additionalDelta;
170 |
171 | // Figure out what the actual character index is in the characterList, and then
172 | // draw the character with the computed offset.
173 | bottomCharIndex = startIndex + ((int) bottomCharPosition * directionAdjustment);
174 |
175 | this.charHeight = charHeight;
176 | this.currentWidth = sourceWidth + (targetWidth - sourceWidth) * animationProgress;
177 | }
178 |
179 | /**
180 | * Draw the current state of the column as it's animating from one character in the list
181 | * to another. This method will take into account various factors such as animation
182 | * progress and the previously interrupted animation state to render the characters
183 | * in the correct position on the canvas.
184 | */
185 | void draw(Canvas canvas, Paint textPaint) {
186 | if (drawText(canvas, textPaint, characterList, bottomCharIndex, bottomDelta)) {
187 | // Save the current drawing state in case our animation gets interrupted
188 | if (bottomCharIndex >= 0) {
189 | currentChar = characterList[bottomCharIndex];
190 | } else if (bottomCharIndex == UNKNOWN_END_INDEX) {
191 | currentChar = targetChar;
192 | }
193 | currentBottomDelta = bottomDelta;
194 | }
195 |
196 | // Draw the corresponding top and bottom characters if applicable
197 | drawText(canvas, textPaint, characterList, bottomCharIndex + 1,
198 | bottomDelta - charHeight);
199 | // Drawing the bottom character here might seem counter-intuitive because we've been
200 | // computing for the bottom character this entire time. But the bottom character
201 | // computed above might actually be above the baseline if we interrupted a previous
202 | // animation that gave us a positive additionalDelta.
203 | drawText(canvas, textPaint, characterList, bottomCharIndex - 1,
204 | bottomDelta + charHeight);
205 | }
206 |
207 | /**
208 | * @return whether the text was successfully drawn on the canvas
209 | */
210 | private boolean drawText(Canvas canvas, Paint textPaint, char[] characterList, int index,
211 | float verticalOffset) {
212 | if (index >= 0 && index < characterList.length) {
213 | canvas.drawText(characterList, index, 1, 0f, verticalOffset, textPaint);
214 | return true;
215 | } else if (startIndex == UNKNOWN_START_INDEX && index == UNKNOWN_START_INDEX) {
216 | canvas.drawText(Character.toString(currentChar), 0, 1, 0f, verticalOffset, textPaint);
217 | return true;
218 | } else if (endIndex == UNKNOWN_END_INDEX && index == UNKNOWN_END_INDEX) {
219 | canvas.drawText(Character.toString(targetChar), 0, 1, 0f, verticalOffset, textPaint);
220 | return true;
221 | }
222 | return false;
223 | }
224 | }
225 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
--------------------------------------------------------------------------------
/ticker/src/main/java/com/robinhood/ticker/TickerView.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (C) 2016 Robinhood Markets, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.robinhood.ticker;
18 |
19 | import android.animation.Animator;
20 | import android.animation.AnimatorListenerAdapter;
21 | import android.animation.ValueAnimator;
22 | import android.annotation.TargetApi;
23 | import android.content.Context;
24 | import android.content.res.Resources;
25 | import android.content.res.TypedArray;
26 | import android.graphics.Canvas;
27 | import android.graphics.Color;
28 | import android.graphics.Paint;
29 | import android.graphics.Rect;
30 | import android.graphics.Typeface;
31 | import android.os.Build;
32 | import android.text.TextPaint;
33 | import android.util.AttributeSet;
34 | import android.util.TypedValue;
35 | import android.view.Gravity;
36 | import android.view.View;
37 | import android.view.animation.AccelerateDecelerateInterpolator;
38 | import android.view.animation.Interpolator;
39 |
40 | /**
41 | * The primary view for showing a ticker text view that handles smoothly scrolling from the
42 | * current text to a given text. The scrolling behavior is defined by
43 | * {@link #setCharacterList(char[])} which dictates what characters come in between the starting
44 | * and ending characters.
45 | *
46 | * This class primarily handles the drawing customization of the ticker view, for example
47 | * setting animation duration, interpolator, colors, etc. It ensures that the canvas is properly
48 | * positioned, and then it delegates the drawing of each column of text to
49 | * {@link TickerColumnManager}.
50 | *
51 | *
This class's API should behave similarly to that of a {@link android.widget.TextView}.
52 | * However, I chose to extend from {@link View} instead of {@link android.widget.TextView}
53 | * because it allows me full flexibility in customizing the drawing and also support different
54 | * customization attributes as they are implemented.
55 | *
56 | * @author Jin Cao, Robinhood
57 | */
58 | public class TickerView extends View {
59 | private static final int DEFAULT_TEXT_SIZE = 12;
60 | private static final int DEFAULT_TEXT_COLOR = Color.BLACK;
61 | private static final int DEFAULT_ANIMATION_DURATION = 350;
62 | private static final Interpolator DEFAULT_ANIMATION_INTERPOLATOR =
63 | new AccelerateDecelerateInterpolator();
64 | private static final int DEFAULT_GRAVITY = Gravity.START;
65 |
66 | protected final Paint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
67 |
68 | private final TickerDrawMetrics metrics = new TickerDrawMetrics(textPaint);
69 | private final TickerColumnManager columnManager = new TickerColumnManager(metrics);
70 | private final ValueAnimator animator = ValueAnimator.ofFloat(1f);
71 |
72 | // Minor optimizations for re-positioning the canvas for the composer.
73 | private final Rect viewBounds = new Rect();
74 |
75 | private int lastMeasuredDesiredWidth, lastMeasuredDesiredHeight;
76 |
77 | // View attributes, defaults are set in init().
78 | private float textSize;
79 | private int textColor;
80 | private long animationDurationInMillis;
81 | private Interpolator animationInterpolator;
82 | private int gravity;
83 | private boolean animateMeasurementChange;
84 |
85 | public TickerView(Context context) {
86 | super(context);
87 | init(context, null, 0, 0);
88 | }
89 |
90 | public TickerView(Context context, AttributeSet attrs) {
91 | super(context, attrs);
92 | init(context, attrs, 0, 0);
93 | }
94 |
95 | public TickerView(Context context, AttributeSet attrs, int defStyleAttr) {
96 | super(context, attrs, defStyleAttr);
97 | init(context, attrs, defStyleAttr, 0);
98 | }
99 |
100 | @TargetApi(Build.VERSION_CODES.LOLLIPOP)
101 | public TickerView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
102 | super(context, attrs, defStyleAttr, defStyleRes);
103 | init(context, attrs, defStyleAttr, defStyleRes);
104 | }
105 |
106 | /**
107 | * We currently only support the following set of XML attributes:
108 | *
109 | * - app:textColor
110 | *
- app:textSize
111 | *
112 | *
113 | * @param context context from constructor
114 | * @param attrs attrs from constructor
115 | * @param defStyleAttr defStyleAttr from constructor
116 | * @param defStyleRes defStyleRes from constructor
117 | */
118 | protected void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
119 | final Resources res = context.getResources();
120 |
121 | int textColor = DEFAULT_TEXT_COLOR;
122 | float textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, DEFAULT_TEXT_SIZE,
123 | res.getDisplayMetrics());
124 | int gravity = DEFAULT_GRAVITY;
125 |
126 | // Set the view attributes from XML or from default values defined in this class
127 | final TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.ticker_TickerView,
128 | defStyleAttr, defStyleRes);
129 |
130 | final int textAppearanceResId = arr.getResourceId(
131 | R.styleable.ticker_TickerView_android_textAppearance, -1);
132 |
133 | // Check textAppearance first
134 | if (textAppearanceResId != -1) {
135 | final TypedArray textAppearanceArr = context.obtainStyledAttributes(
136 | textAppearanceResId,
137 | new int[] {
138 | // TODO: having textColor first here does not work, why?
139 | android.R.attr.textSize,
140 | android.R.attr.textColor,
141 | });
142 |
143 | textSize = textAppearanceArr.getDimension(0, textSize);
144 | textColor = textAppearanceArr.getColor(1, textColor);
145 |
146 | textAppearanceArr.recycle();
147 | }
148 |
149 | // Custom set attributes on the view should override textAppearance if applicable.
150 | gravity = arr.getInt(R.styleable.ticker_TickerView_android_gravity, gravity);
151 | textColor = arr.getColor(R.styleable.ticker_TickerView_android_textColor, textColor);
152 | textSize = arr.getDimension(R.styleable.ticker_TickerView_android_textSize, textSize);
153 |
154 | // After we've fetched the correct values for the attributes, set them on the view
155 | animationInterpolator = DEFAULT_ANIMATION_INTERPOLATOR;
156 | this.animationDurationInMillis = arr.getInt(
157 | R.styleable.ticker_TickerView_ticker_animationDuration, DEFAULT_ANIMATION_DURATION);
158 | this.animateMeasurementChange = arr.getBoolean(
159 | R.styleable.ticker_TickerView_ticker_animateMeasurementChange, false);
160 | this.gravity = gravity;
161 | setTextColor(textColor);
162 | setTextSize(textSize);
163 |
164 | arr.recycle();
165 |
166 | animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
167 | @Override
168 | public void onAnimationUpdate(ValueAnimator animation) {
169 | columnManager.setAnimationProgress(animation.getAnimatedFraction());
170 | checkForRelayout();
171 | invalidate();
172 | }
173 | });
174 | animator.addListener(new AnimatorListenerAdapter() {
175 | @Override
176 | public void onAnimationEnd(Animator animation) {
177 | columnManager.onAnimationEnd();
178 | checkForRelayout();
179 | }
180 | });
181 | }
182 |
183 |
184 | /********** BEGIN PUBLIC API **********/
185 |
186 |
187 | /**
188 | * This is the primary API that the view uses to determine how to animate from one character
189 | * to another. The provided character array dictates what characters will appear between
190 | * the start and end characters.
191 | *
192 | * For example, given the list [a,b,c,d,e], if the view wants to animate from 'd' to 'a',
193 | * it will know that it has to go from 'd' to 'c' to 'b' to 'a', and these are the characters
194 | * that show up during the animation scroll.
195 | *
196 | *
You can find some helpful character list generators in {@link TickerUtils}.
197 | *
198 | *
Special note: the character list must contain {@link TickerUtils#EMPTY_CHAR} because the
199 | * ticker needs to know how to animate from empty to another character (e.g. when the length
200 | * of the string changes).
201 | *
202 | * @param characterList the character array that dictates character orderings.
203 | */
204 | public void setCharacterList(char[] characterList) {
205 | boolean foundEmpty = false;
206 | for (char character : characterList) {
207 | if (character == TickerUtils.EMPTY_CHAR) {
208 | foundEmpty = true;
209 | break;
210 | }
211 | }
212 |
213 | if (!foundEmpty) {
214 | throw new IllegalArgumentException("Missing TickerUtils#EMPTY_CHAR in character list");
215 | }
216 |
217 | columnManager.setCharacterList(characterList);
218 | }
219 |
220 | /**
221 | * Sets the string value to display. If the TickerView is currently empty, then this method
222 | * will immediately display the provided text. Otherwise, it will run the default animation
223 | * to reach the provided text.
224 | *
225 | * @param text the text to display.
226 | */
227 | public void setText(String text) {
228 | setText(text, columnManager.getCurrentWidth() > 0);
229 | }
230 |
231 | /**
232 | * Similar to {@link #setText(String)} but provides the optional argument of whether to
233 | * animate to the provided text or not.
234 | *
235 | * @param text the text to display.
236 | * @param animate whether to animate to text.
237 | */
238 | public synchronized void setText(String text, boolean animate) {
239 | final char[] targetText = text == null ? new char[0] : text.toCharArray();
240 |
241 | if (columnManager.shouldDebounceText(targetText)) {
242 | return;
243 | }
244 |
245 | columnManager.setText(targetText);
246 | setContentDescription(text);
247 |
248 | if (animate) {
249 | // Kick off the animator that draws the transition
250 | if (animator.isRunning()) {
251 | animator.cancel();
252 | }
253 |
254 | animator.setDuration(animationDurationInMillis);
255 | animator.setInterpolator(animationInterpolator);
256 | animator.start();
257 | } else {
258 | columnManager.setAnimationProgress(1f);
259 | columnManager.onAnimationEnd();
260 | checkForRelayout();
261 | invalidate();
262 | }
263 | }
264 |
265 | /**
266 | * @return the current text color that's being used to draw the text.
267 | */
268 | public int getTextColor() {
269 | return textColor;
270 | }
271 |
272 | /**
273 | * Sets the text color used by this view. The default text color is defined by
274 | * {@link #DEFAULT_TEXT_COLOR}.
275 | *
276 | * @param color the color to set the text to.
277 | */
278 | public void setTextColor(int color) {
279 | if (this.textColor != color) {
280 | textColor = color;
281 | textPaint.setColor(textColor);
282 | invalidate();
283 | }
284 | }
285 |
286 | /**
287 | * @return the current text size that's being used to draw the text.
288 | */
289 | public float getTextSize() {
290 | return textSize;
291 | }
292 |
293 | /**
294 | * Sets the text size used by this view. The default text size is defined by
295 | * {@link #DEFAULT_TEXT_SIZE}.
296 | *
297 | * @param textSize the text size to set the text to.
298 | */
299 | public void setTextSize(float textSize) {
300 | if (this.textSize != textSize) {
301 | this.textSize = textSize;
302 | textPaint.setTextSize(textSize);
303 | onTextPaintMeasurementChanged();
304 | }
305 | }
306 |
307 | /**
308 | * @return the current text typeface.
309 | */
310 | public Typeface getTypeface() {
311 | return textPaint.getTypeface();
312 | }
313 |
314 | /**
315 | * Sets the typeface size used by this view.
316 | *
317 | * @param typeface the typeface to use on the text.
318 | */
319 | public void setTypeface(Typeface typeface) {
320 | textPaint.setTypeface(typeface);
321 | onTextPaintMeasurementChanged();
322 | }
323 |
324 | /**
325 | * @return the duration in milliseconds that the transition animations run for.
326 | */
327 | public long getAnimationDuration() {
328 | return animationDurationInMillis;
329 | }
330 |
331 | /**
332 | * Sets the duration in milliseconds that this TickerView runs its transition animations. The
333 | * default animation duration is defined by {@link #DEFAULT_ANIMATION_DURATION}.
334 | *
335 | * @param animationDurationInMillis the duration in milliseconds.
336 | */
337 | public void setAnimationDuration(long animationDurationInMillis) {
338 | this.animationDurationInMillis = animationDurationInMillis;
339 | }
340 |
341 | /**
342 | * @return the interpolator used to interpolate the animated values.
343 | */
344 | public Interpolator getAnimationInterpolator() {
345 | return animationInterpolator;
346 | }
347 |
348 | /**
349 | * Sets the interpolator for the transition animation. The default interpolator is defined by
350 | * {@link #DEFAULT_ANIMATION_INTERPOLATOR}.
351 | *
352 | * @param animationInterpolator the interpolator for the animation.
353 | */
354 | public void setAnimationInterpolator(Interpolator animationInterpolator) {
355 | this.animationInterpolator = animationInterpolator;
356 | }
357 |
358 | /**
359 | * @return the current text gravity used to align the text. Should be one of the values defined
360 | * in {@link android.view.Gravity}.
361 | */
362 | public int getGravity() {
363 | return gravity;
364 | }
365 |
366 | /**
367 | * Sets the gravity used to align the text.
368 | *
369 | * @param gravity the new gravity, should be one of the values defined in
370 | * {@link android.view.Gravity}.
371 | */
372 | public void setGravity(int gravity) {
373 | if (this.gravity != gravity) {
374 | this.gravity = gravity;
375 | invalidate();
376 | }
377 | }
378 |
379 | /**
380 | * Enables/disables the flag to animate measurement changes. If this flag is enabled, any
381 | * animation that changes the content's text width (e.g. 9999 to 10000) will have the view's
382 | * measured width animated along with the text width. However, a side effect of this is that
383 | * the entering/exiting character might get truncated by the view's view bounds as the width
384 | * shrinks or expands.
385 | *
386 | *
Warning: using this feature may degrade performance as it will force a re-measure and
387 | * re-layout during each animation frame.
388 | *
389 | *
This flag is disabled by default.
390 | *
391 | * @param animateMeasurementChange whether or not to animate measurement changes.
392 | */
393 | public void setAnimateMeasurementChange(boolean animateMeasurementChange) {
394 | this.animateMeasurementChange = animateMeasurementChange;
395 | }
396 |
397 | /**
398 | * @return whether or not we are currently animating measurement changes.
399 | */
400 | public boolean getAnimateMeasurementChange() {
401 | return animateMeasurementChange;
402 | }
403 |
404 | /**
405 | * Adds a custom {@link android.animation.Animator.AnimatorListener} to listen to animator
406 | * update events used by this view.
407 | *
408 | * @param animatorListener the custom animator listener.
409 | */
410 | public void addAnimatorListener(Animator.AnimatorListener animatorListener) {
411 | animator.addListener(animatorListener);
412 | }
413 |
414 | /**
415 | * Removes the specified custom {@link android.animation.Animator.AnimatorListener} from
416 | * this view.
417 | *
418 | * @param animatorListener the custom animator listener.
419 | */
420 | public void removeAnimatorListener(Animator.AnimatorListener animatorListener) {
421 | animator.removeListener(animatorListener);
422 | }
423 |
424 |
425 | /********** END PUBLIC API **********/
426 |
427 |
428 | /**
429 | * Force the view to call {@link #requestLayout()} if the new text doesn't match the old bounds
430 | * we set for the previous view state.
431 | */
432 | private void checkForRelayout() {
433 | final boolean widthChanged = lastMeasuredDesiredWidth != computeDesiredWidth();
434 | final boolean heightChanged = lastMeasuredDesiredHeight != computeDesiredHeight();
435 |
436 | if (widthChanged || heightChanged) {
437 | requestLayout();
438 | }
439 | }
440 |
441 | private int computeDesiredWidth() {
442 | final int contentWidth = (int) (animateMeasurementChange ?
443 | columnManager.getCurrentWidth() : columnManager.getMinimumRequiredWidth());
444 | return contentWidth + getPaddingLeft() + getPaddingRight();
445 | }
446 |
447 | private int computeDesiredHeight() {
448 | return (int) metrics.getCharHeight() + getPaddingTop() + getPaddingBottom();
449 | }
450 |
451 | /**
452 | * Re-initialize all of our variables that are dependent on the TextPaint measurements.
453 | */
454 | private void onTextPaintMeasurementChanged() {
455 | metrics.invalidate();
456 | checkForRelayout();
457 | invalidate();
458 | }
459 |
460 | @Override
461 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
462 | final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
463 | final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
464 | int desiredWidth = MeasureSpec.getSize(widthMeasureSpec);
465 | int desiredHeight = MeasureSpec.getSize(heightMeasureSpec);
466 |
467 | lastMeasuredDesiredWidth = computeDesiredWidth();
468 | lastMeasuredDesiredHeight = computeDesiredHeight();
469 |
470 | switch (widthMode) {
471 | case MeasureSpec.EXACTLY:
472 | break;
473 | case MeasureSpec.AT_MOST:
474 | desiredWidth = Math.min(desiredWidth, lastMeasuredDesiredWidth);
475 | break;
476 | case MeasureSpec.UNSPECIFIED:
477 | desiredWidth = lastMeasuredDesiredWidth;
478 | break;
479 | }
480 |
481 | switch (heightMode) {
482 | case MeasureSpec.EXACTLY:
483 | break;
484 | case MeasureSpec.AT_MOST:
485 | desiredHeight = Math.min(desiredHeight, lastMeasuredDesiredHeight);
486 | break;
487 | case MeasureSpec.UNSPECIFIED:
488 | desiredHeight = lastMeasuredDesiredHeight;
489 | break;
490 | }
491 |
492 | setMeasuredDimension(desiredWidth, desiredHeight);
493 | }
494 |
495 | @Override
496 | protected void onSizeChanged(int width, int height, int oldw, int oldh) {
497 | super.onSizeChanged(width, height, oldw, oldh);
498 | viewBounds.set(getPaddingLeft(), getPaddingTop(), width - getPaddingRight(),
499 | height - getPaddingBottom());
500 | }
501 |
502 | @Override
503 | protected void onDraw(Canvas canvas) {
504 | super.onDraw(canvas);
505 |
506 | canvas.save();
507 |
508 | realignAndClipCanvasForGravity(canvas);
509 |
510 | // canvas.drawText writes the text on the baseline so we need to translate beforehand.
511 | canvas.translate(0f, metrics.getCharBaseline());
512 |
513 | columnManager.draw(canvas, textPaint);
514 |
515 | canvas.restore();
516 | }
517 |
518 | private void realignAndClipCanvasForGravity(Canvas canvas) {
519 | final float currentWidth = columnManager.getCurrentWidth();
520 | final float currentHeight = metrics.getCharHeight();
521 | realignAndClipCanvasForGravity(canvas, gravity, viewBounds, currentWidth, currentHeight);
522 | }
523 |
524 | // VisibleForTesting
525 | static void realignAndClipCanvasForGravity(Canvas canvas, int gravity, Rect viewBounds,
526 | float currentWidth, float currentHeight) {
527 | final int availableWidth = viewBounds.width();
528 | final int availableHeight = viewBounds.height();
529 |
530 | float translationX = 0;
531 | float translationY = 0;
532 | if ((gravity & Gravity.CENTER_VERTICAL) == Gravity.CENTER_VERTICAL) {
533 | translationY = viewBounds.top + (availableHeight - currentHeight) / 2f;
534 | }
535 | if ((gravity & Gravity.CENTER_HORIZONTAL) == Gravity.CENTER_HORIZONTAL) {
536 | translationX = viewBounds.left + (availableWidth - currentWidth) / 2f;
537 | }
538 | if ((gravity & Gravity.TOP) == Gravity.TOP) {
539 | translationY = 0;
540 | }
541 | if ((gravity & Gravity.BOTTOM) == Gravity.BOTTOM) {
542 | translationY = viewBounds.top + (availableHeight - currentHeight);
543 | }
544 | if ((gravity & Gravity.START) == Gravity.START) {
545 | translationX = 0;
546 | }
547 | if ((gravity & Gravity.END) == Gravity.END) {
548 | translationX = viewBounds.left + (availableWidth - currentWidth);
549 | }
550 |
551 | canvas.translate(translationX ,translationY);
552 | canvas.clipRect(0f, 0f, currentWidth, currentHeight);
553 | }
554 | }
555 |
--------------------------------------------------------------------------------