当我们的应用在进行耗时操作时,显示一个进度条呈现给用户。让用户知道当前进度是一个非常好的体验,接下来我们就来简单了解下ProgressBar(本文主要针对刚開始学习的人。大神能够绕开啦),先看效果图:
进度条ProgressBar共同拥有几种样式。如圆形,长条形等等,本例中用的是长条形:
style="@android:style/Widget.ProgressBar.Horizontal"进度是由5-0,逆向显示的,也就是一个倒计时。方法主要是Thread+Handler,在线程中通过不断变化的进度值,将消息通过handler传递给主线程并更新UI:
主程序(MainActivity)代码:
package com.example.progressBar;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.annotation.SuppressLint;import android.app.Activity;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity { private ProgressBar progressBar; private TextView progressText; private Button btn; private int progress=5; private Handler handler; @SuppressLint("HandlerLeak") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); progressBar=(ProgressBar) findViewById(R.id.progressBar); progressBar.setProgress(5); progressText=(TextView) findViewById(R.id.progressText); btn=(Button) findViewById(R.id.btn); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { //子线程完毕耗时操作 new Thread(new Task()).start(); } }); //主线程更新UI handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: progressBar.setProgress(progress);//更新进度 progressText.setText(""+progress); break; case 1: progressBar.setProgress(0); progressText.setText("0"); Toast.makeText(getApplicationContext(), "进入游戏。!!
", Toast.LENGTH_SHORT).show(); break; } }; }; } private class Task implements Runnable { @Override public void run() { while (true) { dowork(); Message msg = new Message(); if (progress < 5&&progress>0) { msg.what = 0; handler.sendMessage(msg); } else if (progress <=0) { msg.what = 1; handler.sendMessage(msg); break; } } } } //耗时操作,每运行一次,暂停一秒 private void dowork() { try { Thread.sleep(1000); --progress; } catch (InterruptedException e) { e.printStackTrace(); } } }
布局:
源代码地址: