Android Basics Getting Started tutorial--2.3.7 ProgressBar (progress bar)

Source: Internet
Author: User

Android Basics Getting Started tutorial--2.3.7 ProgressBar (progress bar)

tags (space delimited): Android Basics Getting Started Tutorial

Introduction to this section:

This section brings you the ProgressBar (progress bar) in the Android Basic UI control, and there are many progressbar scenarios, such as
When the user logs in, the background is sending the request, and waiting for the server to return information, this time will use the progress bar, or when doing some comparison
Time consuming operation, need to wait for a long time, this time if no prompt, the user may think that the program Carsh or phone freezes
, which greatly reduces the user experience, so where time-consuming operations are needed, add a progress bar to let the user know the current program
In the execution, you can also intuitively tell the user the progress of the current task, and so on! Using the progress bar can bring me such convenience!
Well, start explaining this section ~
Yes, ProgressBar. Official API Documentation: ProgressBar

1. Common attribute explanation and base instance

From the official documentation, we see a class diagram like this:

ProgressBar inheritance and view classes, direct subclasses have Absseekbar and Contentloadingprogressbar,
The subclasses of Absseekbar have Seekbar and Ratingbar, which is also based on ProgressBar implementation.

General properties in detail:

  • Android:max: Maximum value of the progress bar
  • Android:Progress: Progress bar Completed progress value
  • Android:progressdrawable: Set the Drawable object for the track
  • Android:indeterminate: If set to true, the progress bar does not accurately display the progress
  • Android:indeterminatedrawable: Set drawable object with progress bar not showing progress
  • Android:indeterminateduration: Set the duration of inaccurate display progress
  • Android:secondaryprogress: Two level progress bar, similar to the video playback is the current playback progress, one is the buffering progress, the former through the Progress property settings!

In the corresponding re-java we can call the following methods:

  • Getmax (): Returns the upper limit of the range of this progress bar
  • getprogress (): Return progress
  • getsecondaryprogress (): Returns secondary progress
  • Incrementprogressby (int diff): Specifies the incremental progress
  • isindeterminate (): Indicates whether the progress bar is in indeterminate mode
  • setindeterminate (Boolean indeterminate): setting in indeterminate mode

Let's take a look at the example of the default progress bar provided by the system.

System default Progress bar Usage Example:

Run:

Implementing the Layout code:

<linearlayout xmlns:android="Http://schemas.android.com/apk/res/android"  Xmlns:tools="Http://schemas.android.com/tools"android:layout_width="Match_parent"  android:layout_height="Match_parent"android:orientation="Vertical"  Tools:context=". Mainactivity ">                        <!--system provides a circular progress bar, which in turn is a large medium-to -    <ProgressBarstyle="@android: Style/widget.progressbar.small"android: Layout_width="Wrap_content"android:layout_height="wrap_content" />                            <ProgressBarandroid:layout_width="Wrap_content"android:layout_ Height="wrap_content" />                    <ProgressBarstyle="@android: Style/widget.progressbar.large"android: Layout_width="Wrap_content"android:layout_height="wrap_content" />                            <!--system-provided horizontal progress bar--    <progressbar  style  = "@android: Style/widget.progressbar.horizontal"  android:layout_width  =" match_parent " android:layout_height  =" wrap_content " android:max  ="  class= Hljs-attribute Progress  = "" "/>     <ProgressBarstyle="@android: Style/widget.progressbar.horizontal"android: Layout_width="Match_parent"android:layout_height="Wrap_content"android: Layout_margintop="10DP"android:indeterminate="true" />                                        </linearlayout>

All right, except for the second one. The system has certainly not satisfied our needs!
Below we will explain the actual development of our progress bar processing!

2. Use animations to replace circular progress bars

The first option is to use a set of sequential images to form a frame animation that, when needed, makes the animation visible and does not require
Let the animation not be visible! And this animation, is generally used animationdrawable to achieve! All right, let's go.
Define a animationdrawable file:
PS: Used picture material: progress bar picture material packaging. zip

Run:

implementation steps:
Create a NEW: Anim file in the Res directory, and then make the Amin_pgbar.xml resource file:

<?xml version= "1.0" encoding= "Utf-8"?>  <animation-list xmlns:android="Http://schemas.android.com/apk/res/android" android:oneshot="false" >            <itemandroid:drawable= "@drawable/loading_01"android:duration=" "/>                          <itemandroid:drawable="@drawable/loading_02"android:duration= "/>"                          <itemandroid:drawable="@drawable/loading_03"android:duration ="/>"                          <itemandroid:drawable= "@drawable/loading_04"android:duration=" "/>                          <itemandroid:drawable="@drawable/loading_05"android:duration= "/>"                          <itemandroid:drawable="@drawable/loading_06"android:duration ="/>"                          <itemandroid:drawable= "@drawable/loading_07"android:duration=" "/>                          <itemandroid:drawable="@drawable/loading_08"android:duration= "/>"                          <itemandroid:drawable="@drawable/loading_09"android:duration ="/>"                          <itemandroid:drawable= "@drawable/loading_10"android:duration=" "/>                          <itemandroid:drawable="@drawable/loading_11"android:duration= "/>"                          <itemandroid:drawable="@drawable/loading_12"android:duration ="/>"                      </animation-list>  

Then write a layout file, there is only one imageview can be used to display the progress bar, the SRC set to the above drawable resources can!
and finally to Mainactivity.java.

 Public  class mainactivity extends appcompatactivity {    PrivateImageView Img_pgbar;PrivateAnimationdrawable AD;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Img_pgbar = (ImageView) Findviewbyid (R.id.img_pgbar);        AD = (animationdrawable) img_pgbar.getdrawable (); Img_pgbar.postdelayed (NewRunnable () {@Override             Public void Run() {Ad.start (); }        }, -); }}

Here is just how to start the animation, the rest on your own oh ~ In the need to display the progress bar, let ImageView visible;
Keep him hidden when you don't need it! In fact ProgressBar itself has a indeterminatedrawable, just put
This parameter is set to the animation resources mentioned above, but the pattern size of the progress strips can not be directly modified, need Java code
Modify, if you set the width high, and this width is too large, you will see that there are several progress bars ... Weigh it yourself ~

3. Customizing the circular progress bar

I believe you read 2 will spit groove, lying trough, so pit Dad, take an animation to deceptive, haha, the actual development are so, of course, the above
This is only applicable to situations where the progress is not shown, and if it is not useful to show the progress, well, then look
Online a simple custom circular progress bar! The code is relatively simple, easy to understand, and interesting to look at, or to extend the relevant ~

Run:

Implementation code:

Custom view class:

/** * Created by Jay on 2015/8/5 0005. * * Public  class circlepgbar extends View {    PrivatePaint Mbackpaint;PrivatePaint Mfrontpaint;PrivatePaint Mtextpaint;Private floatMstrokewidth = -;Private floatMhalfstrokewidth = mstrokewidth/2;Private floatMradius = $;PrivateRECTF Mrect;Private intMprogress =0;//target value, change as much as you want    Private intMtargetprogress = -;Private intMmax = -;Private intMwidth;Private intMheight; Public Circlepgbar(Context context) {Super(context);    Init (); } Public Circlepgbar(context context, AttributeSet attrs) {Super(context, attrs);    Init (); } Public Circlepgbar(context context, AttributeSet attrs,intDEFSTYLEATTR) {Super(Context, attrs, defstyleattr);    Init (); }//completion of correlation parameter initialization    Private void Init() {Mbackpaint =NewPaint ();        Mbackpaint.setcolor (Color.White); Mbackpaint.setantialias (true);        Mbackpaint.setstyle (Paint.Style.STROKE);        Mbackpaint.setstrokewidth (Mstrokewidth); Mfrontpaint =NewPaint ();        Mfrontpaint.setcolor (Color.green); Mfrontpaint.setantialias (true);        Mfrontpaint.setstyle (Paint.Style.STROKE);        Mfrontpaint.setstrokewidth (Mstrokewidth); Mtextpaint =NewPaint ();        Mtextpaint.setcolor (Color.green); Mtextpaint.setantialias (true); Mtextpaint.settextsize ( the);    Mtextpaint.settextalign (Paint.Align.CENTER); }//Rewrite the Onmeasure method of measuring size and the core method of Drawing View OnDraw ()    @Override    protected void onmeasure(intWidthmeasurespec,intHEIGHTMEASURESPEC) {Super. Onmeasure (Widthmeasurespec, Heightmeasurespec);        Mwidth = Getrealsize (Widthmeasurespec);        Mheight = Getrealsize (Heightmeasurespec);    Setmeasureddimension (Mwidth, mheight); }@Override    protected void OnDraw(Canvas canvas) {Initrect ();floatAngle = mprogress/(float) Mmax * the; Canvas.drawcircle (Mwidth/2, Mheight/2, Mradius, Mbackpaint); Canvas.drawarc (Mrect,- -, Angle,false, Mfrontpaint); Canvas.drawtext (mprogress +"%", Mwidth/2+ Mhalfstrokewidth, Mheight/2+ Mhalfstrokewidth, mtextpaint);if(Mprogress < mtargetprogress) {mprogress + =1;        Invalidate (); }    } Public int getrealsize(intMEASURESPEC) {intresult =1;intmode = Measurespec.getmode (MEASURESPEC);intSize = Measurespec.getsize (MEASURESPEC);if(mode = = Measurespec.at_most | | mode = = measurespec.unspecified) {//self-calculationresult = (int) (Mradius *2+ mstrokewidth); }Else{result = size; }returnResult }Private void Initrect() {if(Mrect = =NULL) {Mrect =NewRECTF ();intViewsize = (int) (Mradius *2);intleft = (mwidth-viewsize)/2;inttop = (mheight-viewsize)/2;intright = left + viewsize;intBottom = top + viewsize;        Mrect.set (left, top, right, bottom); }    }}

Then add the following in the layout file:

    <com.jay.progressbardemo.CirclePgBar        android:layout_width="match_parent"        android:layout_height="match_parent"/>

It's so simple ~

This section summarizes:

This section introduces common controls in Android: ProgressBar explains basic usage, and the actual development
For the two methods of implementation of the progress bar, the second custom progress bar can be self-improvement, and then use the actual development!
OK, this section is here, thank you ~

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Basics Getting Started tutorial--2.3.7 ProgressBar (progress bar)

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.