Android中ProgressDialog的简单示例

时间:2023-03-09 06:24:12
Android中ProgressDialog的简单示例
网上一般对进度条的示例都是如何显示,没有在任务结束如何关闭的文章,参考其他文章经过试验之后把整套进度条显示的简单示例如下:

建立android工程等工作都略去,Google一下就可以了。

下面来介绍主要的Activity

ProgressBarDemo.java

  1. package com.lveyo.android.demo.progressbar;
  2. import android.app.Activity;
  3. import android.app.ProgressDialog;
  4. import android.os.Bundle;
  5. import android.os.Handler;
  6. import android.os.Message;
  7. import android.view.View;
  8. import android.widget.Button;
  9. import android.widget.TextView;
  10. public class ProgressBarDemo extends Activity {
  11. private TextView statusTextView;
  12. private Button beginBtn;
  13. private ProgressDialog progressDialog;
  14. @Override
  15. public void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. setContentView(R.layout.main);
  18. statusTextView = (TextView)findViewById(R.id.status);
  19. beginBtn = (Button)findViewById(R.id.beginBtn);
  20. setListener();
  21. }
  22. /**
  23. * 用Handler来更新UI
  24. */
  25. private Handler handler = new Handler(){
  26. @Override
  27. public void handleMessage(Message msg) {
  28. //关闭ProgressDialog
  29. progressDialog.dismiss();
  30. //更新UI
  31. statusTextView.setText("Completed!");
  32. }};
  33. /**
  34. * 点击按钮事件listener
  35. */
  36. private void setListener(){
  37. beginBtn.setOnClickListener(new View.OnClickListener() {
  38. @Override
  39. public void onClick(View v) {
  40. //显示ProgressDialog
  41. progressDialog = ProgressDialog.show(ProgressBarDemo.this, "Loading...", "Please wait...", true, false);
  42. //新建线程
  43. new Thread(){
  44. @Override
  45. public void run() {
  46. //需要花时间计算的方法
  47. Calculation.calculate(4);
  48. //向handler发消息
  49. handler.sendEmptyMessage(0);
  50. }}.start();
  51. }
  52. });
  53. }
  54. }

Calculation.java

  1. package com.lveyo.android.demo.progressbar;
  2. /**
  3. * 示意方法
  4. * @author lveyo
  5. *
  6. */
  7. public class Calculation {
  8. public static void calculate(int sleepSeconds){
  9. try {
  10. Thread.sleep(sleepSeconds * 1000);
  11. } catch (Exception e) {
  12. // TODO: handle exception
  13. }
  14. }
  15. }

main.xml文件

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <TextView android:id="@+id/status"
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. android:text="@string/hello"
  11. />
  12. <Button android:id="@+id/beginBtn"
  13. android:layout_width="fill_parent"
  14. android:layout_height="wrap_content"
  15. android:text="begin"
  16. />
  17. </LinearLayout>

在android中,通常我们无法在单独的线程中更新UI,而要在主线程中,这也就是为什么我们要使用 Handler了,当handler收到消息中,它会把它放入到队列中等待执行,通常来说这会很快被执行。

Android中ProgressDialog的简单示例