The Android ProgressBar

  • Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

A list,

A progress bar is a very useful component of a UI interface, often used to show the user the percentage of a time-consuming operation completed. The progress bar can dynamically display the progress, so as to avoid the user feeling that the program is unresponsive when executing a certain operation for a long time, thus improving the user interface friendliness.

Progress bars are generally divided into horizontal (bar) and ring as shown in the figure: almost all patterns of progress bars are mainly of these two types.

Common attributes and methods

The property name meaning
style Set the style of the progress bar
max Set the maximum value of the progress bar
maxHeight Maximum height of progress Widget
miniHeight Minimum height of progress Widget
maxWidth Maximum width of progress Widget
minWidth Minimum width of progress Widget
progress Sets the completed progress value for the progress bar
progressDrawable Custom drawable display
indeteminateDrawable Sets the Drawable object that draws a progress bar that does not show progress
indeterminate If this property is set to true, the progress bar displays inexact progress
indeteminateDuration Sets the duration of imprecise display of progress
secondaryProgress Defines second-level progress values between 0 and Max. The progress is between the main progress and the background. For example, when a video is played on the network, the second-level progress is used to represent the buffering progress, and the main progress is used to represent the playback progress.
interpolator Set the animation speed
indeterminateBehavior Define the behavior of the uncertainty mode when the progress reaches its maximum; The value must be either repeat or cycle, where repeat indicates that the progress restarts from 0; Cycle indicates that progress remains at the current value and returns to 0

Style properties:

  • @ android: style/Widget. The ProgressBar. Horizontal: Horizontal progress bar
  • @ android: style/Widget. The ProgressBar. Inverse: average size of the progress bar
  • @ android: style/Widget. The ProgressBar. Large: big circular progress bar
  • @ android: style/Widget. The ProgressBar. Large. The Inverse: big circular progress bar
  • @ android: style/Widget. The ProgressBar. Small: Small circular progress bar
  • @ android: style/Widget. The ProgressBar. Small. The Inverse: Small circular progress bar

In Java code, we use the following methods:

getMax() GetProgress (): returns progress
getsecondaryProgress() // Return to level 2
incrementProgressBy(int diff) // Specify the progress to be added
isIndeterminate() // Indicates whether the progress bar is in indeterminate mode
setIndeterminate(boolean indeterminate) // Set indeterminate mode
Copy the code

Three, simple use

  1. Writing layout files
<! -- Progress bar provided by the system -->
<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=Horizontal Progress Bar
        android:layout_marginTop="50dp"
        android:layout_gravity="center"/>
    <ProgressBar
        android:id="@+id/progress_01"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:max="100"
        android:layout_marginTop="100dp"
        android:padding="20dp"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"/>
    <TextView
        android:id="@+id/tv_progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/progress_01"
        android:layout_centerHorizontal="true"/>
Copy the code
  1. Write Java code, details in code comments
public class MainActivity extends AppCompatActivity {

    private ProgressBar mProgressBar;
    private TextView mTextView;
    private int start=0,maxprogress;

    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    mTextView.setText(start+"%");// Update progress
                    mProgressBar.setProgress(start);break; }}};@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mProgressBar = findViewById(R.id.progress_01);
        mTextView=findViewById(R.id.tv_progress);
        maxprogress=mProgressBar.getMax();
    }

    @Override
    protected void onStart(a) {
        super.onStart();
        // Start thread loading
    new Thread() {
        @Override
        public void run(a) {
            while (true) {
                try {
                    Thread.sleep(1000);// The thread sleeps for 1s
                    int a = new Random().nextInt(10);// Generate a random number up to 10
                    start += a;
                    if (start > maxprogress)// If the process exceeds the maximum value
                        break;
                    mHandler.sendEmptyMessage(0);// In Android. Instead of updating the UI directly in the thread, we use Hander message processing
                } catch(InterruptedException e) { e.printStackTrace(); } } } }.start(); }}Copy the code

Effect:

Customizing progressBars

Sometimes, the system style of the progress bar is not enough for our needs, in this case we need to customize the progress bar style.

Let’s implement a simple custom progress bar that changes color as it goes from 0 to Max. The color is customizable. The main implementation is to introduce a custom XML resource file throughandroid:progressDrawableProperty to map the ProgressBar to the XML resource file.

The XML resource file in the figure above is:


      
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="5dp"/>
        </shape>
        <! -- Background color -->
        <color android:color="#CCCCCC"/>
    </item>

    <item android:id="@android:id/progress">
        <clip
            android:clipOrientation="horizontal"
            android:gravity="left">
            <shape>
                <corners android:radius="5dp"/>
<! -- Start color, middle color, end color -->
                <gradient
                    android:startColor="#00FF00"
                    android:centerColor="#FFFF00"
                    android:endColor="#FF0000"/>
            </shape>
        </clip>
    </item>
</layer-list>
Copy the code

Layer-list is a hierarchically nested tag that can nest multiple item tags. You can nest various types of tags within an item, such as Shape, bitmap,color, etc. These tags are subclasses of Drawable.

Item label width, height, gravity, left, right, bottom, top… Property that controls the display position of the item neutron tag.

Android tag a lot of, in the future of the custom control will often use, can understand, the follow-up to other controls I will add.

A simple, flashy custom progress bar is ready to use as in the previous example.