Android Studio實(shí)現(xiàn)進(jìn)度條效果
本文實(shí)例為大家分享了Android Studio實(shí)現(xiàn)進(jìn)度條效果的具體代碼,供大家參考,具體內(nèi)容如下
實(shí)驗(yàn)作業(yè) 要求一個(gè)進(jìn)度條,進(jìn)度隨機(jī)
效果圖
xml代碼
<?xml version='1.0' encoding='utf-8'?><RelativeLayout xmlns:android='http://schemas.android.com/apk/res/android' xmlns:app='http://schemas.android.com/apk/res-auto' xmlns:tools='http://schemas.android.com/tools' android:layout_width='match_parent' android:layout_height='match_parent' android:orientation='vertical' tools:context='.ProgressBarActivity'> <ProgressBarandroid: android:layout_width='match_parent'android:layout_height='wrap_content' android:backgroundTint='@color/purple_200'android:progress='25'android:max='100'android:layout_centerVertical='true'/> <TextViewandroid:layout_width='match_parent'android:layout_height='wrap_content'android:text='ProgressBar'android:textSize='28sp'android:gravity='center'android:layout_below='@+id/pb_determinate'/></RelativeLayout>
java代碼
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 */@Overridepublic 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;// } //獲取一個(gè)隨機(jī)數(shù)給到currentProgress然后顯示出來 currentProgress = random.nextInt(100); mHandler.sendEmptyMessage(0);} } catch (InterruptedException e){e.printStackTrace(); }} }}.start(); }}
線程里的for循環(huán)可以去掉,循環(huán)是測(cè)試定時(shí)加長(zhǎng)進(jìn)度條設(shè)計(jì)的。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
