页面上有ProgressBar控件和一个按键,点击按键将启动线程,该线程控制进度条以1秒为间隔,步长为5显示进度,直至100%停止。
项目截图
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 android:orientation="vertical" 8 tools:context=".MainActivity"> 9 10 <TextView 11 android:layout_width="wrap_content" 12 android:layout_height="wrap_content" 13 android:text="进度条显示" 14 android:textSize="24sp" /> 15 16 <ProgressBar 17 android:id="@+id/progressBar" 18 style="?android:attr/progressBarStyleHorizontal" 19 android:layout_width="match_parent" 20 android:layout_height="49dp" /> 21 22 <Button 23 android:id="@+id/button" 24 android:layout_width="wrap_content" 25 android:layout_height="wrap_content" 26 android:text="启动进度条" /> 27 28 </LinearLayout>
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 package com.example.handletest; 2 3 import android.os.Handler; 4 import android.os.Message; 5 import android.support.v7.app.AppCompatActivity; 6 import android.os.Bundle; 7 import android.view.View; 8 import android.widget.Button; 9 import android.widget.ProgressBar; 10 11 public class MainActivity extends AppCompatActivity { 12 13 private ProgressBar progressBar; 14 private Button mButton; 15 16 @Override 17 protected void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState); 19 setContentView(R.layout.activity_main); 20 progressBar = (ProgressBar)findViewById(R.id.progressBar); 21 mButton = (Button)findViewById(R.id.button); 22 final Handler handler = new Handler(){ 23 @Override 24 public void dispatchMessage(Message msg) { 25 super.dispatchMessage(msg); 26 if(msg.what==1){ 27 int pos = msg.arg1; 28 progressBar.setProgress(pos); 29 } 30 } 31 }; 32 33 34 mButton.setOnClickListener(new View.OnClickListener() { 35 @Override 36 public void onClick(View v) { 37 new Thread(){ 38 @Override 39 public void run() { 40 super.run(); 41 int pos = 0; 42 while(pos<100){ 43 pos += 5; 44 Message msg = new Message(); 45 msg.what=1; 46 msg.arg1=pos; 47 handler.sendMessage(msg); 48 try{ 49 Thread.sleep(1000); 50 }catch(InterruptedException e){ 51 e.printStackTrace(); 52 } 53 } 54 } 55 }.start(); 56 } 57 }); 58 } 59 }
这道题真的水,不是我想用handler,是题目规定的
虽然说android更新ui界面只能在主线程完成,但是progressBar 本身已经有对子线程进行处理。所以完全可以不用handler就能直接在子线程对progressBar进行更新。