Android Custom view implementation with digital progress bar Instance code _android

Source: Internet
Author: User
Tags getcolor

The first step, the effect show

Figure 1, Blue progress bar

Figure 2, Red progress bar

Figure 3, a number of different colors of the progress bar

Figure 4, a number of different colors of the progress bar

Step two, custom ProgressBar to implement a progress bar with numbers

0. Project structure


As shown in the figure above: the library project is a concrete implementation of a custom Numberprogressbar with a digital progress bar, and the demo project refers to the library project in engineering-dependent ways for the sample project. Then use the custom Numberprogressbar with the digital progress bar to do the show


As shown in the figure above: the structure Chart of a library project with a digital progress bar customized


As shown in the figure above: the chart of the demo project

1. Analysis of drawing steps

As shown in the above figures. This progress bar can be divided into the following three parts:


Reacherd Area: A progress bar (rectangle) that represents the text before the current progress value

Text area: Represents the current progress value literal

Unreacherd Area: progress bar (rectangular) After the current progress value text

According to the above analysis, we want to implement the progress bar with a number, only to follow the following three steps to achieve:

1. Draw Reacherd Area (progress bar of text before current progress value)

2, Draw the text area (the current progress value texts)

3, Draw Unreacherd area (the current progress value text after the progress bar) can be.

2, Custom properties

Because we found that the above three parts of the color, font size, the maximum progress bar, indicating the height of the rectangle of the progress bar, and so on can be changed to show different interface effects.

So we do all of these attributes as custom attributes. This allows us to define its attributes in XML, just as the components provided by the Android official.

1. Define your own property profile: Attr.xml

Define a Attrs.xml file under the Res/values file, Res/values/attrs.xml define the code as follows:

 <?xml version= "1.0" encoding= "Utf-8"?> <resources> <declare-styleable Name= the current progress value of the "Numberprogressbar" > <!--progress bar--> <attr name= "progress_current" format= "integer"/> <!-- The progress bar's maximum progress value--> <attr name= "Progress_max" format= "integer"/> <!--the progress bar color after the current progress value text--> <attr " Progress_unreached_color "format=" Color "/> <!--progress bar colors before the current progress value text--> <attr name=" Progress_reached_color " format= "Color"/> <!--the height of the progress bar before the current progress value text--> <attr name= "Progress_reached_bar_height" format= "Dimension"/ > <!--the height of the progress bar after the current progress value text--> <attr name= "Progress_unreached_bar_height" format= "Dimension"/> <!-- The font size of the current progress value text--> <attr name= "progress_text_size" format= "Dimension"/> <!--the color of the current progress value text--> <attr name= "Progress_text_color" format= "Color"/> <!--the spacing of text before the current progress value--> <attr name= "Progress_text_offset" Dimension "/> <!--whether the current progress value text is visible--> <attr name=" progress_text_visibility "format= "enum" > <enum name= "visible" value= "0"/> "<enum name=" Invisible "value=" 1 "/> </attr> </ declare-styleable> <declare-styleable name= "Themes" > <attr name= "Numberprogressbarstyle" Reference "/> </declare-styleable> </resources> 

2, the definition of the theme profile: Styles.xml

Define a Styles.xml file under the Res/values file, which defines some basic theme options in case the user can choose to use it. The Res/values/styles.xml definition code looks like this:

&lt;?xml version= "1.0" encoding= "Utf-8"?&gt; &lt;resources&gt; &lt;style name= "Numberprogressbar_default" &gt; &lt; Item Name= "Android:layout_height" &gt;wrap_content&lt;/item&gt; &lt;item name= "Android:layout_width" &gt;match_ parent&lt;/item&gt; &lt;item name= "Progress_max" &gt;100&lt;/item&gt; &lt;item name= "Progress_current" &gt;0&lt;/ item&gt; &lt;item name= "Progress_unreached_color" &gt; #CCCCCC &lt;/item&gt; &lt;item name= "Progress_reached_color" &gt; #3498DB &lt;/item&gt; &lt;item name= "progress_text_size" &gt;10sp&lt;/item&gt; &lt;item name= "Progress_text_ Color "&gt; #3498DB &lt;/item&gt; &lt;item name=" progress_reached_bar_height "&gt;1.5dp&lt;/item&gt; &lt;item name=" Progress_unreached_bar_height "&gt;0.75dp&lt;/item&gt; &lt;/style&gt; &lt;style name=" Numberprogressbar_passing_ Green "&gt; &lt;item name=" android:layout_height "&gt;wrap_content&lt;/item&gt; &lt;item name=" Android:layout_width " &gt;match_parent&lt;/item&gt; &lt;item name= "Progress_max" &gt;100&lt;/item&gt; &lt;item name= "Progress_cur"Rent "&gt;0&lt;/item&gt; &lt;item name=" Progress_unreached_color "&gt; #CCCCCC &lt;/item&gt; &lt;item name=" Progress_ Reached_color "&gt; #70A800 &lt;/item&gt; &lt;item name=" progress_text_size "&gt;10sp&lt;/item&gt; &lt;item name="
Progress_text_color "&gt; #70A800 &lt;/item&gt; &lt;item name=" Progress_reached_bar_height "&gt;1.5dp&lt;/item&gt; &lt;item name= "Progress_unreached_bar_height" &gt;0.75dp&lt;/item&gt; &lt;/style&gt; &lt;style name= " Numberprogressbar_beauty_red "&gt; &lt;item name=" android:layout_height "&gt;wrap_content&lt;/item&gt; &lt;item name = "Android:layout_width" &gt;match_parent&lt;/item&gt; &lt;item name= "Progress_max" &gt;100&lt;/item&gt; &lt;item Name= "Progress_current" &gt;0&lt;/item&gt; &lt;item name= "Progress_unreached_color" &gt; #CCCCCC &lt;/item&gt; &lt; Item Name= "Progress_reached_color" &gt; #FF3D7F &lt;/item&gt; &lt;item name= "Progress_text_size" &gt;10sp&lt;/item &gt; &lt;item name= "Progress_text_color" &gt; #FF3D7F &lt;/item&gt; &lt;item name= "Progress_reached_bar_height" &gt; 1.5dp&lt;/item&gt; &lt;item name= "progress_unreached_bar_height" &gt;0.75dp&lt;/item&gt; &lt;/style&gt; &lt;style name= " Numberprogressbar_warning_red "&gt; &lt;item name=" android:layout_height "&gt;wrap_content&lt;/item&gt; &lt;item Name= "Android:layout_width" &gt;match_parent&lt;/item&gt; &lt;item name= "Progress_max" &gt;100&lt;/item&gt; &lt;
Item Name= "Progress_current" &gt;0&lt;/item&gt; &lt;item name= "Progress_unreached_color" &gt; #CCCCCC &lt;/item&gt; &lt;item name= "Progress_reached_color" &gt; #E74C3C &lt;/item&gt; &lt;item name= "Progress_text_size" &gt;10sp&lt;/ item&gt; &lt;item name= "Progress_text_color" &gt; #E74C3C &lt;/item&gt; &lt;item name= "Progress_reached_bar_height" &gt;1.5dp&lt;/item&gt; &lt;item name= "Progress_unreached_bar_height" &gt;0.75dp&lt;/item&gt; &lt;/style&gt; &lt;
Style name= "Numberprogressbar_relax_blue" &gt; &lt;item name= "android:layout_height" &gt;wrap_content&lt;/item&gt; &lt;item name= "Android:layout_width" &gt;match_parent&lt;/item&gt; &lt;item name= "Progress_max" &gt;100&lt;/item&gt; &lt;item name= "progress_current" &gt;0&lt;/item&gt; &lt;item name= "Progress_unreached_color" &gt; #CCCCCC &lt;/ item&gt; &lt;item name= "Progress_reached_color" &gt; #6DBCDB &lt;/item&gt; &lt;item name= "Progress_text_size" &gt;10sp &lt;/item&gt; &lt;item name= "Progress_text_color" &gt; #6DBCDB &lt;/item&gt; &lt;item name= "Progress_reached_bar_
Height "&gt;1.5dp&lt;/item&gt; &lt;item name=" Progress_unreached_bar_height "&gt;0.75dp&lt;/item&gt; &lt;/style&gt; &lt;style name= "Numberprogressbar_grace_yellow" &gt; &lt;item name= "android:layout_height" &gt;wrap_content&lt;/ item&gt; &lt;item name= "android:layout_width" &gt;match_parent&lt;/item&gt; &lt;item name= "Progress_max" &gt;100&lt; /item&gt; &lt;item name= "progress_current" &gt;0&lt;/item&gt; &lt;item name= "Progress_unreached_color" &gt; #CCCCCC &lt;/item&gt; &lt;item name= "Progress_reached_color" &gt; #FFC73B &lt;/item&gt; &lt;item name= "Progress_text_size" &gt;10sp&lt;/item&gt; &lt;item name= "Progress_text_color" &gt; #FFC73B &lt;/item&gt; &lt;item name= "ProgreSs_reached_bar_height "&gt;1.5dp&lt;/item&gt; &lt;item name=" Progress_unreached_bar_height "&gt;0.75dp&lt;/item &gt; &lt;/style&gt; &lt;style name= "Numberprogressbar_funny_orange" &gt; &lt;item name= "Android:layout_height" &gt; wrap_content&lt;/item&gt; &lt;item name= "android:layout_width" &gt;match_parent&lt;/item&gt; &lt;item name= " Progress_max "&gt;100&lt;/item&gt; &lt;item name=" progress_current "&gt;0&lt;/item&gt; &lt;item name=" Progress_ Unreached_color "&gt; #CCCCCC &lt;/item&gt; &lt;item name=" Progress_reached_color "&gt; #FF530D &lt;/item&gt; &lt;item Name= "Progress_text_size" &gt;10sp&lt;/item&gt; &lt;item name= "Progress_text_color" &gt; #FF530D &lt;/item&gt; &lt; Item Name= "Progress_reached_bar_height" &gt;1.5dp&lt;/item&gt; &lt;item name= "Progress_unreached_bar_height" &gt; 0.75dp&lt;/item&gt; &lt;/style&gt; &lt;style name= "Numberprogressbar_twinkle_night" &gt; &lt;item name= "android:
Layout_height "&gt;wrap_content&lt;/item&gt; &lt;item name=" Android:layout_width "&gt;match_parent&lt;/item&gt; &lt;itEM name= "Progress_max" &gt;100&lt;/item&gt; &lt;item name= "progress_current" &gt;0&lt;/item&gt; &lt;item name= "
Progress_unreached_color "&gt; #CCCCCC &lt;/item&gt; &lt;item name=" Progress_reached_color "&gt; #ECF0F1 &lt;/item&gt; &lt;item name= "Progress_text_size" &gt;10sp&lt;/item&gt; &lt;item name= "Progress_text_color" &gt; #ECF0F1 &lt;/item &gt; &lt;item name= "progress_reached_bar_height" &gt;1.5dp&lt;/item&gt; &lt;item name= "Progress_unreached_bar_" Height "&gt;0.75dp&lt;/item&gt; &lt;/style&gt; &lt;/resources&gt;

3, custom view implementation with a digital progress bar

Package Com.daimajia.numberprogressbar;
Import Android.content.Context;
Import Android.content.res.TypedArray;
Import Android.graphics.Canvas;
Import Android.graphics.Color;
Import Android.graphics.Paint;
Import Android.graphics.RectF;
Import Android.os.Bundle;
Import android.os.Parcelable;
Import Android.util.AttributeSet;
Import Android.view.View;
Import static com.daimajia.numberprogressbar.NumberProgressBar.ProgressTextVisibility.Invisible;
Import static com.daimajia.numberprogressbar.NumberProgressBar.ProgressTextVisibility.Visible;
/** * Created by Daimajia on 14-4-30. * * public class Numberprogressbar extends View {/** * Maximum progress value/private int mmaxprogress =/** * Current progress, C
An is not exceed the max progress.
* Current progress value, can not exceed the maximum progress value * * Private int mcurrentprogress = 0;
/** * The progress area bar color.
* Current progress value text before the progress bar color */private int mreachedbarcolor;
/** * the bar unreached area color.
* Current progress value text after the progress bar color/private int munreachedbarcolor;
/** * The progress text color. * Current progress Value Text color * * private int mtextcolor;
/** * The progress text size.
* Current progress value text font size * * Private float mtextsize;
/** * The height of the reached area.
* The height of the progress bar before the current progress value text * * Private float mreachedbarheight;
/** * The height of the unreached area.
* The height of the progress bar after the current progress value text * * Private float munreachedbarheight;
/** * The suffix of the number.
* The percentage suffix of the current progress value */private String Msuffix = "%";
/** * the prefix.
* percent prefix for current progress value/private String mprefix = "";
The default color of the current progress value text private final int default_text_color = COLOR.RGB (66, 145, 241);
The font size of the current progress value text private final float default_text_size;
Default progress bar before current progress value private final int default_reached_color = COLOR.RGB (66, 145, 241);
Default progress bar After current progress value private final int default_unreached_color = COLOR.RGB (204, 204, 204);
The default spacing of text before the current progress value private final float default_progress_text_offset;
The default height of the progress bar before the current progress value text is private final float default_reached_bar_height;
The default height of the progress bar after the current progress value text private final float default_unreached_bar_height; /** * For Save and restore instance of ProGressbar.
* * private static final String instance_state = "Saved_instance";
private static final String Instance_text_color = "Text_color";
private static final String instance_text_size = "Text_size";
private static final String instance_reached_bar_height = "Reached_bar_height";
private static final String Instance_reached_bar_color = "Reached_bar_color";
private static final String instance_unreached_bar_height = "Unreached_bar_height";
private static final String Instance_unreached_bar_color = "Unreached_bar_color";
private static final String Instance_max = "MAX";
private static final String instance_progress = "PROGRESS";
private static final String Instance_suffix = "SUFFIX";
private static final String Instance_prefix = "PREFIX";
private static final String instance_text_visibility = "text_visibility";
The default display current progress value text 0 is displayed, 1 is not showing private static final int progress_text_visible = 0;
/** * The width of the ' text ' to be drawn.
* The width of the text of the current progress value to draw * * Private float mdrawtextwidth;
/*** The drawn text start.
* The starting position of the text of the current progress value to draw * * Private float Mdrawtextstart;
/** * The drawn text end.
* The end position of the text of the current progress value to draw * * Private float mdrawtextend;
/** * The text that is drawn in OnDraw ().
* Text of the current progress value to be drawn/private String mcurrentdrawtext;
/** * The Paint of the reached area.
* Draw the brush of the progress bar before the current progress value text/private Paint mreachedbarpaint;
/** * The Paint of the unreached area.
* Draw the brush of the progress bar after the current progress value text/private Paint munreachedbarpaint;
/** * The Paint of the progress text.
* Draw the current progress value text of the brush/private Paint mtextpaint;
/** * unreached bar area to draw rect. * progress bar (Rectangle) After the current progress value text/private RECTF MUNREACHEDRECTF = new RECTF (0, 0, 0, 0);
/** * reached bar area rect. * The progress bar (rectangle) of the text before the current progress value */private RECTF MREACHEDRECTF = new RECTF (0, 0, 0, 0);
/** * The progress text offset.
* Current progress value before the spacing of the text * * Private float Moffset;
/** * Determine if need to draw unreached area.
* Whether the progress bar after the current progress value is drawn * * Private Boolean Mdrawunreachedbar = true;
/** * The progress bar before the current progress value is drawn * * Private Boolean Mdrawreachedbar = true;
/*** Whether to draw the current progress value text/private Boolean mifdrawtext = true;
/** * Listener/private Onprogressbarlistener Mlistener; 
public enum Progresstextvisibility {Visible, invisible} public numberprogressbar (context, NULL); 
Public Numberprogressbar (context, AttributeSet attrs) {This (context, attrs, R.attr.numberprogressbarstyle);} Public Numberprogressbar (context, AttributeSet attrs, int defstyleattr) {Super (context, attrs, defstyleattr); de
Fault_reached_bar_height = dp2px (1.5f);
Default_unreached_bar_height = dp2px (1.0f);
Default_text_size = sp2px (10);
Default_progress_text_offset = dp2px (3.0f); Get custom properties Final TypedArray attributes = Context.gettheme (). Obtainstyledattributes (Attrs,
R.styleable.numberprogressbar, defstyleattr, 0); Mreachedbarcolor = Attributes.getcolor (R.styleable.numberprogressbar_progress_reached_color, Default_reached_
color); Munreachedbarcolor = Attributes.getcolor (R.styleable.numberprogressbar_progress_unreached_color, default_unreAched_color);
Mtextcolor = Attributes.getcolor (R.styleable.numberprogressbar_progress_text_color, Default_text_color);
Mtextsize = Attributes.getdimension (r.styleable.numberprogressbar_progress_text_size, default_text_size); Mreachedbarheight = Attributes.getdimension (R.styleable.numberprogressbar_progress_reached_bar_height, Default_
Reached_bar_height); Munreachedbarheight = Attributes.getdimension (R.styleable.numberprogressbar_progress_unreached_bar_height,
Default_unreached_bar_height); Moffset = Attributes.getdimension (R.styleable.numberprogressbar_progress_text_offset, Default_progress_text_
Offset); int textvisible = Attributes.getint (r.styleable.numberprogressbar_progress_text_visibility, PROGRESS_TEXT_VISIBLE)
; if (textvisible!= progress_text_visible) {mifdrawtext = false;} setprogress (Attributes.getint (
R.styleable.numberprogressbar_progress_current, 0));
Setmax (Attributes.getint (R.styleable.numberprogressbar_progress_max, 100)); Recycle TypedArray, which can be reused for subsequent calls. Recycle to Typedarraypool Pool, in preparation for later use Attributes.recycle ();
Initializepainters (); @Override protected int Getsuggestedminimumwidth () {return (int) mtextsize;} @Override protected int Getsuggestedminim
Umheight () {return Math.max (int) mtextsize, Math.max ((int) mreachedbarheight, (int) munreachedbarheight)); @Override The value of the protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {/** * measurespec parameter is int, which is divided into 32-bit high and low 16, * High 32-bit saved Is Specmode, the low 16-bit represents specsize, * * Specmode three: 1, measurespec.unspecified, the parent view does not impose any restrictions on the child view, children can get the size of any desired; 2,
measurespec.exactly, the parent view expects the size of the child view to be the size specified in Specsize, 3, Measurespec.at_most, and the size of the child view at most specsize.
*/setmeasureddimension (Measure (Widthmeasurespec, true), measure (Heightmeasurespec, false)); private int measure (int measurespec, Boolean iswidth) {int result; int mode = Measurespec.getmode (measurespec); int siz
E = Measurespec.getsize (MEASURESPEC); int padding = iswidth?
Getpaddingleft () + getpaddingright (): Getpaddingtop () + Getpaddingbottom (); The/** parent determines the exact size of the child, and the child is limited to the given bounds, ignoring the size it wants.
(When the width or height is match_parent, the mode is exactly because the child view occupies the space of the remaining container, so its size is OK) */if (mode = = measurespec.exactly) {result =
Size 
else {result = Iswidth getsuggestedminimumwidth (): Getsuggestedminimumheight (), result + = padding,/** * Child maximum attainable size specified * (When set to Wrap_content, the mode is At_most, which indicates the maximum size of the child view, so that the child view will set its own size according to the upper limit) */if (mode = = Measurespec.at_most) {if (Iswid
TH) {result = Math.max (result, size);} else {result = Math.min (result, size);}
return result; } @Override protected void OnDraw (Canvas Canvas) {//If you want to draw the current progress value text if (mifdrawtext) {CALCULATEDRAWRECTF ();} else {calculatedrawrectfwithoutprogresstext ();}//If the progress bar before the current progress value is to be drawn if (Mdrawreachedbar) {Canvas.drawrect (
MREACHEDRECTF, Mreachedbarpaint); //If you want to draw the progress bar after the current progress value (Mdrawunreachedbar) {canvas.drawrect (MUNREACHEDRECTF, munreachedbarpaint);}//Draw the current progress value text if (
Mifdrawtext) Canvas.drawtext (Mcurrentdrawtext, Mdrawtextstart, Mdrawtextend, Mtextpaint); }/** * Initialization brush/private void Initializepainters () {mreachedbarpaint =New Paint (Paint.anti_alias_flag);
Mreachedbarpaint.setcolor (Mreachedbarcolor);
Munreachedbarpaint = new Paint (Paint.anti_alias_flag);
Munreachedbarpaint.setcolor (Munreachedbarcolor);
Mtextpaint = new Paint (Paint.anti_alias_flag);
Mtextpaint.setcolor (Mtextcolor);
Mtextpaint.settextsize (mtextsize); /** * Calculates the properties of the graphic when you do not draw the current progress value text/private void Calculatedrawrectfwithoutprogresstext () {//Current progress value does not draw//the properties of the progress bar (rectangle) before the current progress value M
Reachedrectf.left = Getpaddingleft ();
Mreachedrectf.top = GetHeight ()/2.0f-mreachedbarheight/2.0f; Mreachedrectf.right = (getwidth ()-Getpaddingleft ()-getpaddingright ())/(Getmax () * 1.0f) * getprogress () + getpadding
Left ();
Mreachedrectf.bottom = GetHeight ()/2.0f + mreachedbarheight/2.0f;
The properties of the progress bar (rectangle) After the current progress value munreachedrectf.left = Mreachedrectf.right;
Munreachedrectf.right = GetWidth ()-getpaddingright ();
Munreachedrectf.top = GetHeight ()/2.0f +-munreachedbarheight/2.0f;
Munreachedrectf.bottom = GetHeight ()/2.0f + munreachedbarheight/2.0f; }
/**
* The various properties of the graphic when you want to draw the current progress value text/private void CALCULATEDRAWRECTF () {////Text Mcurrentdrawtext = String.Format for the current progress value to draw ("%d", Getpro
Gress () * 100/getmax ());
Mcurrentdrawtext = mprefix + Mcurrentdrawtext + msuffix;
The width of the text of the current progress value to draw mdrawtextwidth = Mtextpaint.measuretext (Mcurrentdrawtext); If the current progress value is 0, the progress bar before the current progress value is not drawn if (getprogress () = = 0) {Mdrawreachedbar = false; Mdrawtextstart = Getpaddingleft ();}//otherwise drawn
The progress bar before the current progress value text else {Mdrawreachedbar = true;//The properties of the progress bar (rectangle) before the current progress value text Mreachedrectf.left = Getpaddingleft ();
Mreachedrectf.top = GetHeight ()/2.0f-mreachedbarheight/2.0f; Mreachedrectf.right= (GetWidth ()-Getpaddingleft ()-getpaddingright ())/(Getmax () * 1.0f) * getprogress ()-Moffset + G
Etpaddingleft ();
Mreachedrectf.bottom = GetHeight ()/2.0f + mreachedbarheight/2.0f;
The starting position of the text for the current progress value Mdrawtextstart = (mreachedrectf.right + moffset);
///The end position of the text of the current progress value mdrawtextend = (int) (GetHeight ()/2.0f)-((Mtextpaint.descent () + mtextpaint.ascent ())/2.0f)); If you can't draw the text of the current progress value, recalculate the currentThe starting position of the text of the degree value and the right if ((Mdrawtextstart + mdrawtextwidth) &gt;= getwidth ()-getpaddingright ()) {for the progress bar (rectangle) preceding the current progress value) {
Mdrawtextstart = GetWidth ()-Getpaddingright ()-mdrawtextwidth;
Mreachedrectf.right = Mdrawtextstart-moffset;
The starting position of the progress bar after the current progress value text float Unreachedbarstart = mdrawtextstart + mdrawtextwidth + moffset; If the progress bar after the progress value text is not drawn, the progress bar after the progress value is not drawn if (Unreachedbarstart &gt;= getwidth ()-getpaddingright ()) {Mdrawunreachedbar = False
;
} else {Mdrawunreachedbar = true;//The properties of the progress bar (rectangle) After the current progress value text Munreachedrectf.left = Unreachedbarstart;
Munreachedrectf.right = GetWidth ()-getpaddingright ();
Munreachedrectf.top = GetHeight ()/2.0f +-munreachedbarheight/2.0f;
Munreachedrectf.bottom = GetHeight ()/2.0f + munreachedbarheight/2.0f;
}/** * Get progress text color.
* Gets the current progress value text color * @return Progress text color.
* * public int gettextcolor () {return mtextcolor;}/** * Get progress Text size.
* Gets the font size of the current progress value text * @return Progress text size. * * Public float getprogresstextsize () {return mTeXtsize; /** * Gets the progress bar color after the current progress value text */public int getunreachedbarcolor () {return munreachedbarcolor;}/** * Gets the progress bar color before the current progress value text * * p ublic int Getreachedbarcolor () {return mreachedbarcolor;}/** * Gets the current progress value of the progress bar/public int getprogress () {return Mcurren
tprogress; /** * Get the maximum progress bar/public int Getmax () {return mmaxprogress;}/** * Get the height of the progress bar before the current progress value text * * * Public float Getreachedbarhe Ight () {return mreachedbarheight}/** * Gets the height of the progress bar after the current progress value text * * Public float getunreachedbarheight () {return munreachedb
Arheight; /** * Set the font size of the current progress value text * @param textsize the font size of the current progress value text * * public void setprogresstextsize (float textsize) {this.mtextsize
= Textsize;
Mtextpaint.settextsize (mtextsize);
Invalidate (); /** * Set the color of the current progress value text * @param textcolor the current progress value text color/public void Setprogresstextcolor (int textcolor) {This.mtextcolor =
TextColor;
Mtextpaint.setcolor (Mtextcolor);
Invalidate (); /** * Set the progress bar color after the current progress value text * @param barcolor the progress bar color after the current progress value text/public void Setunreachedbarcolor (int barcolor) {This.munReachedbarcolor = Barcolor;
Munreachedbarpaint.setcolor (Munreachedbarcolor);
Invalidate (); /** * Set progress bar color before current progress value text * @param progresscolor the progress bar color before the current progress value text/public void Setreachedbarcolor (int progresscolor) {th
Is.mreachedbarcolor = Progresscolor;
Mreachedbarpaint.setcolor (Mreachedbarcolor);
Invalidate (); /** * Set the height of the progress bar before the current progress value text * @param height of the progress bar before the current progress value text of the height */public void Setreachedbarheight (float height) {Mreachedbar
Height = height; /** * Set the height of the progress bar after the current progress value text * @param height of the progress bar after the current progress value text of the height */public void Setunreachedbarheight (float height) {Munreache
Dbarheight = height; /** * Set the maximum value of the progress value * @param maxprogress the maximum of the progress value * * public void Setmax (int maxprogress) {if (maxprogress &gt; 0) {this.mma
xprogress = maxprogress;
Invalidate (); }/** * Sets the suffix of the current progress value text * @param suffix the suffix of the current progress value text */public void Setsuffix (String suffix) {if (suffix = null) {Msuffix = "";
}
else {msuffix = suffix;}} /** * Gets the suffix of the current progress value text/public String Getsuffix () {return msuffix;}/** * Sets the prefix of the current progress value text *@param prefix the current progress value text prefix */public void Setprefix (String prefix) {if (prefix = = null) Mprefix = "";
else {mprefix = prefix;}} /** * Gets the prefix of the current progress value text/public String Getprefix () {return mprefix;}/** * Set the progress bar's current progress value increase * @param by increase how much * * public void in Crementprogressby (int by) {if (by &gt; 0) {setprogress (getprogress () + by);} if (Mlistener!= null) {//callback Onprogresscha
Nge () method to handle the event Mlistener.onprogresschange (Getprogress (), Getmax ()) After the change of the progress value; /** * Set Current progress value * * @param progress Current progress value/public void setprogress (int progress) {if (Progress &lt;= getmax () &AMP;&A mp
Progress &gt;= 0) {this.mcurrentprogress = progress; invalidate ();}} @Override protected parcelable onsaveinstancestate () {final Bundle Bundle = new Bundle (); Bundle.putparcelable (Instance_
State, Super.onsaveinstancestate ());
Bundle.putint (Instance_text_color, GetTextColor ());
Bundle.putfloat (Instance_text_size, Getprogresstextsize ());
Bundle.putfloat (Instance_reached_bar_height, Getreachedbarheight ()); Bundle.putfloat (Instance_unreached_bar_height, Getunreachedbarheight ());
Bundle.putint (Instance_reached_bar_color, Getreachedbarcolor ());
Bundle.putint (Instance_unreached_bar_color, Getunreachedbarcolor ());
Bundle.putint (Instance_max, Getmax ());
Bundle.putint (Instance_progress, getprogress ());
Bundle.putstring (Instance_suffix, Getsuffix ());
Bundle.putstring (Instance_prefix, Getprefix ());
Bundle.putboolean (Instance_text_visibility, getprogresstextvisibility ());
return bundle;  } @Override protected void Onrestoreinstancestate (parcelable state) {if (state instanceof Bundle) {final Bundle Bundle =
(Bundle) state;
Mtextcolor = Bundle.getint (Instance_text_color);
Mtextsize = Bundle.getfloat (instance_text_size);
Mreachedbarheight = Bundle.getfloat (instance_reached_bar_height);
Munreachedbarheight = Bundle.getfloat (instance_unreached_bar_height);
Mreachedbarcolor = Bundle.getint (Instance_reached_bar_color);
Munreachedbarcolor = Bundle.getint (Instance_unreached_bar_color);
Initializepainters (); Setmax (Bundle. GetInt (Instance_max));
Setprogress (Bundle.getint (instance_progress));
Setprefix (bundle.getstring (Instance_prefix));
Setsuffix (bundle.getstring (Instance_suffix)); Setprogresstextvisibility (Bundle.getboolean (instance_text_visibility)?
visible:invisible);
Super.onrestoreinstancestate (Bundle.getparcelable (instance_state));
Return
} super.onrestoreinstancestate (state); /** * DP to PX */public float dp2px (float dp) {final FLOAT scale = getresources (). Getdisplaymetrics (). density; return DP
* scale + 0.5f; }/** * SP to PX */public float sp2px (float sp) {final float scale = getresources (). Getdisplaymetrics (). scaleddensity; Retu
RN SP * SCALE; /** * Sets whether to draw the current progress value text/public void setprogresstextvisibility (progresstextvisibility visibility) {Mifdrawtext = Visibili
ty = = Visible;
Invalidate (); /** * Gets whether to draw the current progress value text/public boolean getprogresstextvisibility () {return mifdrawtext;}/** * Listener/Public V when the progress value changes OID Setonprogressbarlistener (Onprogressbarlistener listener) {Mlistener = ListeNer }
}

As shown in the above code:

In the custom Numberprogressbar control's construction method, you get all the custom property values that are set up and use the default custom property values if there are no settings.

The onmeasure (int widthmeasurespec, int heightmeasurespec) method is then overridden to determine the size of the custom Numberprogressbar control.

Then rewrite the OnDraw () method to draw a custom, digitally-drawn progress bar.

Step three, add a custom digitally-defined progress bar to your layout file

Define a Activity_main.xml file in the Res/layout directory, and the Res/layout/activity_main.xml definition code looks like this:

&lt;linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http:// Schemas.android.com/tools "xmlns:custom=" Http://schemas.android.com/apk/res-auto "android:layout_width=" Match_ Parent "android:layout_height=" match_parent "android:paddingleft=" @dimen/activity_horizontal_margin "Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" Android: paddingbottom= "@dimen/activity_vertical_margin" android:orientation= "vertical" tools:context= "
Com.daimajia.numberprogressbar.example.mainactivity= "&gt; &lt;com.daimajia.numberprogressbar.numberprogressbar Android:id= "@+id/numberbar1" android:layout_width= "wrap_content" android:padding= "20DP" custom:progress_current= " 0 "style=" @style/numberprogressbar_default "android:layout_height=" Wrap_content "/&gt; &lt; Com.daimajia.numberprogressbar.NumberProgressBar android:id= "@+id/numberbar2" android:layout_height= "Wrap_ Content "android:padding=" 20DP "custom:progress_current=" 20"Android:layout_width=" match_parent "style=" @style/numberprogressbar_passing_green "/&gt; &lt; Com.daimajia.numberprogressbar.NumberProgressBar android:id= "@+id/numberbar3" android:layout_margin= "20DP" style= "@style/numberprogressbar_relax_blue" custom:progress_current= "android:layout_height=" Wrap_content "/&gt; &lt; Com.daimajia.numberprogressbar.NumberProgressBar android:id= "@+id/numberbar4" android:layout_width= "wrap_content "Android:layout_margin=" 20DP "style=" @style/numberprogressbar_grace_yellow "custom:progress_current=" "Android: layout_height= "Wrap_content"/&gt; &lt;com.daimajia.numberprogressbar.numberprogressbar android:id= "@+id/" Numberbar5 "android:layout_width=" wrap_content "android:layout_margin=" 20DP "custom:progress_current=" "style=" @ Style/numberprogressbar_warning_red "android:layout_height=" Wrap_content "/&gt; &lt; Com.daimajia.numberprogressbar.NumberProgressBar android:id= "@+id/numberbar6" android:layout_width= "wrap_content "Android:layout_margin=" 20DP "style="@style/numberprogressbar_funny_orange" custom:progress_current= "android:layout_height=" Wrap_content "/&gt;" &lt;com.daimajia.numberprogressbar.numberprogressbar android:id= "@+id/numberbar7" android:layout_width= "Wrap_
Content "android:layout_margin=" 20DP "style=" "@style/numberprogressbar_beauty_red" custom:progress_current= "70" android:layout_height= "Wrap_content"/&gt; &lt;com.daimajia.numberprogressbar.numberprogressbar android:id= "@+id/" Numberbar8 "android:layout_width=" wrap_content "android:layout_margin=" 20DP "style=" @style/numberprogressbar_ Twinkle_night "custom:progress_current=" android:layout_height= "Wrap_content"/&gt; &lt; Com.daimajia.numberprogressbar.NumberProgressBar android:id= "@+id/numberbar9" android:layout_width= "wrap_content "Android:layout_margin=" 20DP "custom:progress_current=" custom:progress_max= "Custom:progress_unreached_" Color= "#FF530D" custom:progress_reached_color= "#6DBCDB" custom:progress_text_size= "10SP" Custom:progress_text_ Color= "#ECF0F1" custom:progress_reached_bar_height= "1.5DP" custom:progress_unreached_bar_height= "0.75DP" android:layout_height= "Wrap_ Content "/&gt; &lt;/LinearLayout&gt;

Step fourth, write the activity load layout file, display a customized progress bar with numbers

The mainactity code looks like this:

 package com.daimajia.numberprogressbar.example; import android.app.Activity; import
Android.graphics.Color;
Import Android.os.Bundle;
Import Android.widget.Toast;
Import Com.daimajia.numberprogressbar.NumberProgressBar;
Import Com.daimajia.numberprogressbar.OnProgressBarListener;
Import Java.util.Timer;
Import Java.util.TimerTask; public class Mainactivity extends activity implements Onprogressbarlistener {private timer timer; private NUMBERPROGRESSB
AR BNP;
Private Numberprogressbar bnp9; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (
R.layout.activity_main);
BNP = (Numberprogressbar) Findviewbyid (R.ID.NUMBERBAR1);
Bnp.setonprogressbarlistener (this);
BNP9 = (Numberprogressbar) Findviewbyid (R.ID.NUMBERBAR9);
Bnp9.setprefix ("Ouyangpeng:");
Bnp9.setsuffix ("% CSDN");
Bnp9.setprogresstextsize (20);
Bnp9.setprogresstextcolor (Color.yellow); Bnp9.setprogresstextvisibility (NUMBERPROGRESSBAR.PROGRESSTEXTVIsibility.
Visible);
Bnp9.setunreachedbarcolor (color.red);
Bnp9.setreachedbarheight (10);
Bnp9.setreachedbarheight (5);
Timer = new timer (); Timer.schedule (New TimerTask () {@Override public void run () {Runonuithread (new Runnable () {@Override public void run ()
{Bnp.incrementprogressby (1);}
});
}, 1000, 100); @Override protected void OnDestroy () {Super.ondestroy (); Timer.cancel ();} @Override public void onprogresschange (int c urrent, int max) {if (current = = max) {Toast.maketext (Getapplicationcontext (), getString (r.string.finish), toast.length
_short). Show ();
Bnp.setprogress (0); }
}
}

The displayed effect diagram is:

After reading the introduction, the reader can go to the following address to see the complete project code

The original address of the project on the GitHub of Daimajia

Https://github.com/daimajia/NumberProgressBar

Here is another example of a numberprogresbar, as shown in the following figure


The above content is small series to introduce the Android custom view to realize with a number of progress bar instance code, I hope to help you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.