How to use Studio to implement Progress Bar in Android
This article mainly introduces how to use Studio to achieve progress bar in Android, the article is very detailed, has a certain reference value, interested friends must read it!
XML code
Java code
package com.example.a18101352;import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.widget.ProgressBar;import java.util.Random;public class MainActivity extends AppCompatActivity { private ProgressBar progressBar; private int maxProgress; private int currentProgress = 0; private Handler mHandler = new Handler(){ /** * Subclasses must implement this to receive messages. * * @param msg */ @Override public void handleMessage(@NonNull Message msg) { super.handleMessage(msg); switch (msg.what){ case 0: progressBar.setProgress(currentProgress); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_progress_bar); progressBar = findViewById(R.id.pb_determinate); maxProgress = progressBar.getMax(); } @Override protected void onStart(){ super.onStart(); new Thread() { private Random random; @Override public void run(){ while(true){ try { for(int i = 0; i
< maxProgress; ++i){ //间隔一秒 Thread.sleep(1000); random = new Random();// currentProgress += 10;// if(currentProgress >maxProgress){// break;// } //Get a random number to currentProgress and display it currentProgress = random.nextInt(100); mHandler.sendEmptyMessage(0); } } catch (InterruptedException e){ e.printStackTrace(); } } } }.start(); }}
Thread in the for loop can be removed, loop is the test timing lengthened progress bar design.
That's all for "How to use Studio to implement progress bars in Android." Thanks for reading! Hope to share the content to help everyone, more relevant knowledge, welcome to pay attention to the industry information channel!