当我们的应用在进行耗时操作时,显示一个进度条呈现给用户,让用户知道当前进度是一个很好的体验,接下来我们就来简单了解下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(); } } }
布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="开始"/> <ProgressBar android:id="@+id/progressBar" android:layout_width="match_parent" android:layout_height="3dp" android:layout_centerInParent="true" android:max="5" style="@android:style/Widget.ProgressBar.Horizontal"/> <TextView android:id="@+id/progressText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_below="@+id/progressBar" android:text="5" android:textSize="20sp"/> </RelativeLayout>