19 |
20 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # android-custom-view-tutorial
2 |
3 | Android Studio project that provides an example application demonstrating the custom views created in the tutorial series
4 | [Android Custom Views][1]. The code for the custom views is located in a library module within the project.
5 |
6 | ## Value Selector
7 |
8 | View to allow the selection of a numeric value by pressing plus/minus buttons. Pressing and holding a
9 | button will update the value repeatedly.
10 | This view can be configured with a minimum and maximum value. There is also a label that will
11 | display below the current value.
12 |
13 | 
14 |
15 | ## Value Bar
16 |
17 | View that displays a colored bar as a ratio of an integer value to a maximum value. There is also a circle
18 | indicator and text that displays at the position of the current value, as well as a label (positioned above the bar).
19 | The maximum value is displayed to the right of the bar.
20 |
21 | 
22 |
23 | [1]: http://www.intertech.com/Blog/android-custom-view-tutorial-part-1-combining-existing-views/
24 |
--------------------------------------------------------------------------------
/customviews/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 |
--------------------------------------------------------------------------------
/app/src/main/java/com/intertech/customviewsexample/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.intertech.customviewsexample;
2 |
3 | import android.support.v7.app.AppCompatActivity;
4 | import android.os.Bundle;
5 | import android.view.View;
6 | import android.widget.Button;
7 |
8 | import com.intertech.customviews.ValueBar;
9 | import com.intertech.customviews.ValueSelector;
10 |
11 | public class MainActivity extends AppCompatActivity {
12 |
13 | @Override
14 | protected void onCreate(Bundle savedInstanceState) {
15 | super.onCreate(savedInstanceState);
16 | setContentView(R.layout.activity_main);
17 |
18 | final ValueSelector valueSelector = (ValueSelector) findViewById(R.id.valueSelector);
19 | valueSelector.setMinValue(0);
20 | valueSelector.setMaxValue(100);
21 |
22 | final ValueBar valueBar = (ValueBar) findViewById(R.id.valueBar);
23 | valueBar.setMaxValue(100);
24 | valueBar.setAnimated(true);
25 | valueBar.setAnimationDuration(4000l);
26 |
27 | Button updateButton = (Button) findViewById(R.id.updateButton);
28 | updateButton.setOnClickListener(new View.OnClickListener() {
29 | @Override
30 | public void onClick(View view) {
31 | int value = valueSelector.getValue();
32 | valueBar.setValue(value);
33 |
34 | //code to use Object Animation instead of the built-in ValueBar animation
35 | //if you use this, be sure the call valueBar.setAnimated(false);
36 | /*
37 | ObjectAnimator anim = ObjectAnimator.ofInt(valueBar, "value", valueBar.getValue(), value);
38 | anim.setDuration(1000);
39 | anim.start();
40 | */
41 | }
42 | });
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/customviews/src/main/res/layout/value_selector.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
15 |
16 |
24 |
25 |
36 |
37 |
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
12 |
13 |
19 |
20 |
21 |
22 |
29 |
30 |
50 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/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 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
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 Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
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 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/customviews/src/main/java/com/intertech/customviews/ValueSelector.java:
--------------------------------------------------------------------------------
1 | package com.intertech.customviews;
2 |
3 | import android.content.Context;
4 | import android.os.Handler;
5 | import android.util.AttributeSet;
6 | import android.view.MotionEvent;
7 | import android.view.View;
8 | import android.widget.RelativeLayout;
9 | import android.widget.TextView;
10 |
11 | /**
12 | * View to allow the selection of a numeric value by pressing plus/minus buttons. Pressing and holding
13 | * a button will update the value repeatedly.
14 | *
15 | * This view can be configured with a minimum and maximum value. There is also a label that will
16 | * display below the current value.
17 | *
18 | *
19 | */
20 | public class ValueSelector extends RelativeLayout {
21 |
22 | private int minValue = Integer.MIN_VALUE;
23 | private int maxValue = Integer.MAX_VALUE;
24 |
25 | private boolean plusButtonIsPressed = false;
26 | private boolean minusButtonIsPressed = false;
27 | private final long REPEAT_INTERVAL_MS = 100l;
28 |
29 | View rootView;
30 | TextView valueTextView;
31 | View minusButton;
32 | View plusButton;
33 |
34 | Handler handler = new Handler();
35 |
36 | public ValueSelector(Context context) {
37 | super(context);
38 | init(context);
39 | }
40 |
41 | public ValueSelector(Context context, AttributeSet attrs) {
42 | super(context, attrs);
43 | init(context);
44 | }
45 |
46 | public ValueSelector(Context context, AttributeSet attrs, int defStyle) {
47 | super(context, attrs, defStyle);
48 | init(context);
49 | }
50 |
51 | /**
52 | * Get the current minimum value that is allowed
53 | *
54 | * @return
55 | */
56 | public int getMinValue() {
57 | return minValue;
58 | }
59 |
60 | /**
61 | * Set the minimum value that will be allowed
62 | *
63 | * @param minValue
64 | */
65 | public void setMinValue(int minValue) {
66 | this.minValue = minValue;
67 | }
68 |
69 | /**
70 | * Get the current maximum value that is allowed
71 | *
72 | * @return
73 | */
74 | public int getMaxValue() {
75 | return maxValue;
76 | }
77 |
78 | /**
79 | * Set the maximum value that will be allowed
80 | *
81 | * @param maxValue
82 | */
83 | public void setMaxValue(int maxValue) {
84 | this.maxValue = maxValue;
85 | }
86 |
87 | /**
88 | * Get the current value
89 | *
90 | * @return the current value
91 | */
92 | public int getValue() {
93 | return Integer.valueOf(valueTextView.getText().toString());
94 | }
95 |
96 | /**
97 | * Set the current value. If the passed in value exceeds the current min or max, the value
98 | * will be set to the respective min/max.
99 | *
100 | * @param newValue new value
101 | */
102 | public void setValue(int newValue) {
103 | int value = newValue;
104 | if(newValue < minValue) {
105 | value = minValue;
106 | } else if (newValue > maxValue) {
107 | value = maxValue;
108 | }
109 |
110 | valueTextView.setText(String.valueOf(value));
111 | }
112 |
113 | private void init(Context context) {
114 | rootView = inflate(context, R.layout.value_selector, this);
115 | valueTextView = (TextView) rootView.findViewById(R.id.valueTextView);
116 |
117 | minusButton = rootView.findViewById(R.id.minusButton);
118 | plusButton = rootView.findViewById(R.id.plusButton);
119 |
120 | minusButton.setOnClickListener(new View.OnClickListener() {
121 | @Override
122 | public void onClick(View v) {
123 | decrementValue();
124 | }
125 | });
126 | minusButton.setOnLongClickListener(
127 | new View.OnLongClickListener() {
128 | @Override
129 | public boolean onLongClick(View arg0) {
130 | minusButtonIsPressed = true;
131 | handler.post(new AutoDecrementer());
132 | return false;
133 | }
134 | }
135 | );
136 | minusButton.setOnTouchListener(new View.OnTouchListener() {
137 | @Override
138 | public boolean onTouch(View v, MotionEvent event) {
139 | if ((event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL)) {
140 | minusButtonIsPressed = false;
141 | }
142 | return false;
143 | }
144 | });
145 |
146 | plusButton.setOnClickListener(new View.OnClickListener() {
147 | @Override
148 | public void onClick(View v) {
149 | incrementValue();
150 | }
151 | });
152 | plusButton.setOnLongClickListener(
153 | new View.OnLongClickListener() {
154 | @Override
155 | public boolean onLongClick(View arg0) {
156 | plusButtonIsPressed = true;
157 | handler.post(new AutoIncrementer());
158 | return false;
159 | }
160 | }
161 | );
162 |
163 | plusButton.setOnTouchListener(new View.OnTouchListener() {
164 | @Override
165 | public boolean onTouch(View v, MotionEvent event) {
166 | if ((event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL)) {
167 | plusButtonIsPressed = false;
168 | }
169 | return false;
170 | }
171 | });
172 | }
173 |
174 | private void incrementValue() {
175 | int currentVal = Integer.valueOf(valueTextView.getText().toString());
176 | if(currentVal < maxValue) {
177 | valueTextView.setText(String.valueOf(currentVal + 1));
178 | }
179 | }
180 |
181 | private void decrementValue() {
182 | int currentVal = Integer.valueOf(valueTextView.getText().toString());
183 | if(currentVal > minValue) {
184 | valueTextView.setText(String.valueOf(currentVal - 1));
185 | }
186 | }
187 |
188 | private class AutoIncrementer implements Runnable {
189 | @Override
190 | public void run() {
191 | if(plusButtonIsPressed){
192 | incrementValue();
193 | handler.postDelayed( new AutoIncrementer(), REPEAT_INTERVAL_MS);
194 | }
195 | }
196 | }
197 | private class AutoDecrementer implements Runnable {
198 | @Override
199 | public void run() {
200 | if(minusButtonIsPressed){
201 | decrementValue();
202 | handler.postDelayed(new AutoDecrementer(), REPEAT_INTERVAL_MS);
203 | }
204 | }
205 | }
206 | }
207 |
--------------------------------------------------------------------------------
/customviews/src/main/java/com/intertech/customviews/ValueBar.java:
--------------------------------------------------------------------------------
1 | package com.intertech.customviews;
2 |
3 | import android.animation.ValueAnimator;
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.graphics.Rect;
10 | import android.graphics.RectF;
11 | import android.graphics.Typeface;
12 | import android.os.Parcel;
13 | import android.os.Parcelable;
14 | import android.util.AttributeSet;
15 | import android.view.View;
16 |
17 | /**
18 | * View that displays a colored bar as a ratio of an integer value to a maximum value. There is also a circle
19 | * indicator and text that displays at the position of the current value, as well as a label (positioned above the bar).
20 | * The maximum value is displayed to the right of the bar.
21 | *
22 | *
See {@link R.styleable#ValueBar ValueBar Attributes}
23 | */
24 | public class ValueBar extends View {
25 |
26 | private int maxValue = 100;
27 | private int currentValue = 0;
28 |
29 | private boolean animated;
30 | private float valueToDraw; //for use during an animation
31 | private long animationDuration = 4000l; //4 second default. this is the time it takes to traverse the entire bar
32 | ValueAnimator animation = null;
33 |
34 | //instance variables for storing xml attributes
35 | private int barHeight;
36 | private int circleRadius;
37 | private int spaceAfterBar;
38 | private int circleTextSize;
39 | private int maxValueTextSize;
40 | private int labelTextSize;
41 | private int labelTextColor;
42 | private int currentValueTextColor;
43 | private int circleTextColor;
44 | private int baseColor;
45 | private int fillColor;
46 |
47 | private String labelText;
48 |
49 | //objects used for drawing
50 | private Paint labelPaint;
51 | private Paint maxValuePaint;
52 | private Paint barBasePaint;
53 | private Paint barFillPaint;
54 | private Paint circlePaint;
55 | private Paint currentValuePaint;
56 |
57 |
58 | public ValueBar(Context context, AttributeSet attrs) {
59 | super(context, attrs);
60 | init(context, attrs);
61 | }
62 |
63 | /**
64 | * Set the maximum value that will be allowed
65 | *
66 | * @param maxValue
67 | */
68 | public void setMaxValue(int maxValue) {
69 | this.maxValue = maxValue;
70 | invalidate();
71 | requestLayout();
72 | }
73 |
74 | /**
75 | * Sets the value of the bar. If the passed in value exceeds the maximum, the value
76 | * will be set to the maximum.
77 | *
78 | * @param newValue
79 | */
80 | public void setValue(int newValue) {
81 | int previousValue = currentValue;
82 | if(newValue < 0) {
83 | currentValue = 0;
84 | } else if (newValue > maxValue) {
85 | currentValue = maxValue;
86 | } else {
87 | currentValue = newValue;
88 | }
89 |
90 | if(animation != null) {
91 | animation.cancel();
92 | }
93 |
94 | if(animated) {
95 | animation = ValueAnimator.ofFloat(previousValue, currentValue);
96 | //animationDuration specifies how long it should take to animate the entire graph, so the
97 | //actual value to use depends on how much the value needs to change
98 | int changeInValue = Math.abs(currentValue - previousValue);
99 | long durationToUse = (long) (animationDuration * ((float) changeInValue / (float) maxValue));
100 | animation.setDuration(durationToUse);
101 |
102 | animation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
103 | @Override
104 | public void onAnimationUpdate(ValueAnimator valueAnimator) {
105 | valueToDraw = (float) valueAnimator.getAnimatedValue();
106 | ValueBar.this.invalidate();
107 | }
108 | });
109 |
110 | animation.start();
111 | } else {
112 | valueToDraw = currentValue;
113 | }
114 |
115 | invalidate();
116 | }
117 |
118 | /**
119 | * Get the current value
120 | *
121 | * @return
122 | */
123 | public int getValue() {
124 | return currentValue;
125 | }
126 |
127 | private void init(Context context, AttributeSet attrs) {
128 | setSaveEnabled(true);
129 |
130 | //read xml attributes
131 | TypedArray ta = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ValueBar, 0, 0);
132 | barHeight = ta.getDimensionPixelSize(R.styleable.ValueBar_barHeight, 0);
133 | circleRadius = ta.getDimensionPixelSize(R.styleable.ValueBar_circleRadius, 0);
134 | spaceAfterBar = ta.getDimensionPixelSize(R.styleable.ValueBar_spaceAfterBar, 0);
135 | circleTextSize = ta.getDimensionPixelSize(R.styleable.ValueBar_circleTextSize, 0);
136 | maxValueTextSize = ta.getDimensionPixelSize(R.styleable.ValueBar_maxValueTextSize, 0);
137 | labelTextSize = ta.getDimensionPixelSize(R.styleable.ValueBar_labelTextSize, 0);
138 | labelTextColor = ta.getColor(R.styleable.ValueBar_labelTextColor, Color.BLACK);
139 | currentValueTextColor = ta.getColor(R.styleable.ValueBar_maxValueTextColor, Color.BLACK);
140 | circleTextColor = ta.getColor(R.styleable.ValueBar_circleTextColor, Color.BLACK);
141 | baseColor = ta.getColor(R.styleable.ValueBar_baseColor, Color.BLACK);
142 | fillColor = ta.getColor(R.styleable.ValueBar_fillColor, Color.BLACK);
143 | labelText = ta.getString(R.styleable.ValueBar_labelText);
144 | ta.recycle();
145 |
146 | labelPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
147 | labelPaint.setTextSize(labelTextSize);
148 | labelPaint.setColor(labelTextColor);
149 | labelPaint.setTextAlign(Paint.Align.LEFT);
150 | labelPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
151 |
152 | maxValuePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
153 | maxValuePaint.setTextSize(maxValueTextSize);
154 | maxValuePaint.setColor(currentValueTextColor);
155 | maxValuePaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
156 | maxValuePaint.setTextAlign(Paint.Align.RIGHT);
157 |
158 | barBasePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
159 | barBasePaint.setColor(baseColor);
160 |
161 | barFillPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
162 | barFillPaint.setColor(fillColor);
163 |
164 | circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
165 | circlePaint.setColor(fillColor);
166 |
167 | currentValuePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
168 | currentValuePaint.setTextSize(circleTextSize);
169 | currentValuePaint.setColor(circleTextColor);
170 | currentValuePaint.setTextAlign(Paint.Align.CENTER);
171 | }
172 |
173 | private int measureHeight(int measureSpec) {
174 |
175 | int size = getPaddingTop() + getPaddingBottom();
176 | size += labelPaint.getFontSpacing();
177 | float maxValueTextSpacing = maxValuePaint.getFontSpacing();
178 | size += Math.max(maxValueTextSpacing, Math.max(barHeight, circleRadius * 2));
179 |
180 | return resolveSizeAndState(size, measureSpec, 0);
181 | }
182 |
183 | private int measureWidth(int measureSpec) {
184 |
185 | int size = getPaddingLeft() + getPaddingRight();
186 | Rect bounds = new Rect();
187 | labelPaint.getTextBounds(labelText, 0, labelText.length(), bounds);
188 | size += bounds.width();
189 |
190 | bounds = new Rect();
191 | String maxValueText = String.valueOf(maxValue);
192 | maxValuePaint.getTextBounds(maxValueText, 0, maxValueText.length(), bounds);
193 | size += bounds.width();
194 |
195 | return resolveSizeAndState(size, measureSpec, 0);
196 | }
197 |
198 | @Override
199 | protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
200 | setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec));
201 | }
202 |
203 | @Override
204 | protected void onDraw (Canvas canvas) {
205 | drawLabel(canvas);
206 | drawBar(canvas);
207 | drawMaxValue(canvas);
208 | }
209 |
210 | private void drawLabel(Canvas canvas) {
211 | float x = getPaddingLeft();
212 | //the y coordinate marks the bottom of the text, so we need to factor in the height
213 | Rect bounds = new Rect();
214 | labelPaint.getTextBounds(labelText, 0, labelText.length(), bounds);
215 | float y = getPaddingTop() + bounds.height();
216 | canvas.drawText(labelText, x, y, labelPaint);
217 | }
218 |
219 | private void drawBar(Canvas canvas) {
220 | String maxValueString = String.valueOf(maxValue);
221 | Rect maxValueRect = new Rect();
222 | maxValuePaint.getTextBounds(maxValueString, 0, maxValueString.length(), maxValueRect);
223 | float barLength = getWidth() - getPaddingRight() - getPaddingLeft() - circleRadius - maxValueRect.width() - spaceAfterBar;
224 |
225 | float barCenter = getBarCenter();
226 |
227 | float halfBarHeight = barHeight / 2;
228 | float top = barCenter - halfBarHeight;
229 | float bottom = barCenter + halfBarHeight;
230 | float left = getPaddingLeft();
231 | float right = getPaddingLeft() + barLength;
232 | RectF rect = new RectF(left, top, right, bottom);
233 | canvas.drawRoundRect(rect, halfBarHeight, halfBarHeight, barBasePaint);
234 |
235 |
236 | float percentFilled = (float) valueToDraw / (float) maxValue;
237 | float fillLength = barLength * percentFilled;
238 | float fillPosition = left + fillLength;
239 | RectF fillRect = new RectF(left, top, fillPosition, bottom);
240 | canvas.drawRoundRect(fillRect, halfBarHeight, halfBarHeight, barFillPaint);
241 |
242 | canvas.drawCircle(fillPosition, barCenter, circleRadius, circlePaint);
243 |
244 | Rect bounds = new Rect();
245 | String valueString = String.valueOf(Math.round(valueToDraw));
246 | currentValuePaint.getTextBounds(valueString, 0, valueString.length(), bounds);
247 | float y = barCenter + (bounds.height() / 2);
248 | canvas.drawText(valueString, fillPosition, y, currentValuePaint);
249 | }
250 |
251 | private void drawMaxValue(Canvas canvas) {
252 | String maxValue = String.valueOf(this.maxValue);
253 | Rect maxValueRect = new Rect();
254 | maxValuePaint.getTextBounds(maxValue, 0, maxValue.length(), maxValueRect);
255 |
256 | float xPos = getWidth() - getPaddingRight();
257 | float yPos = getBarCenter() + maxValueRect.height() / 2;
258 | canvas.drawText(maxValue, xPos, yPos, maxValuePaint);
259 |
260 | }
261 |
262 | private float getBarCenter() {
263 | //position the bar slightly below the middle of the drawable area
264 | float barCenter = (getHeight() - getPaddingTop() - getPaddingBottom()) / 2; //this is the center
265 | barCenter += getPaddingTop() + .1f * getHeight(); //move it down a bit
266 | return barCenter;
267 | }
268 |
269 | /**
270 | * Indicate whether or not the graph should use animation when the value is changed. If true, the
271 | * indicator will "slide" to the new value.
272 | *
273 | *
See {@link #setAnimationDuration(long)}
274 | *
275 | * @param animated whether or not the graph should use animation
276 | */
277 | public void setAnimated(boolean animated) {
278 | this.animated = animated;
279 | }
280 |
281 | /**
282 | * Set the time (in milliseconds) that the animation should use to traverse the entire graph. The actual
283 | * value used will depend on how much tha value changes.
284 | *
285 | * @param animationDuration duration of the animation
286 | */
287 | public void setAnimationDuration(long animationDuration) {
288 | this.animationDuration = animationDuration;
289 | }
290 |
291 | @Override
292 | public Parcelable onSaveInstanceState() {
293 | Parcelable superState = super.onSaveInstanceState();
294 | SavedState ss = new SavedState(superState);
295 | ss.value = currentValue;
296 | return ss;
297 | }
298 |
299 | @Override
300 | public void onRestoreInstanceState(Parcelable state) {
301 | SavedState ss = (SavedState) state;
302 | super.onRestoreInstanceState(ss.getSuperState());
303 | currentValue = ss.value;
304 | valueToDraw = currentValue; //set valueToDraw directly to prevent re-animation
305 | }
306 |
307 | private static class SavedState extends BaseSavedState {
308 | int value;
309 |
310 | SavedState(Parcelable superState) {
311 | super(superState);
312 | }
313 |
314 | private SavedState(Parcel in) {
315 | super(in);
316 | value = in.readInt();
317 | }
318 |
319 | @Override
320 | public void writeToParcel(Parcel out, int flags) {
321 | super.writeToParcel(out, flags);
322 | out.writeInt(value);
323 | }
324 |
325 | public static final Parcelable.Creator CREATOR
326 | = new Parcelable.Creator() {
327 | public SavedState createFromParcel(Parcel in) {
328 | return new SavedState(in);
329 | }
330 |
331 | public SavedState[] newArray(int size) {
332 | return new SavedState[size];
333 | }
334 | };
335 | }
336 | }
337 |
--------------------------------------------------------------------------------