灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:2057回复:0

Android 程式开发:(一)详解活动 —— 1.5 显示进度对话框

楼主#
更多 发布于:2012-09-06 14:03

当要进行耗时的操作的时候,往往会看见“请稍候”字样的对话框。例如,用户正在登入服务器,此时并不允许用户使用这个软件,或者应用程序把结果返回给用户之前,要进行某些耗时的计算。在这些情况下,显示一个“进度条”对话框,能友好地让用户等待,同时也能阻止用户进行某些不必要的操作。
1、创建一个工程:Dialog。


2、main.xml中的代码。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:layout_width="fill_parent"
    Android:layout_height="fill_parent"
    Android:orientation="vertical" >

    <Button
        Android:id="@+id/btn_dialog2"
        Android:layout_width="fill_parent"
        Android:layout_height="wrap_content"
        Android:onClick="onClick2"
        Android:text="Click to display a progress dialog" />

</LinearLayout>
3、DialogActivity.java中的代码。package net.horsttnann.Dialog;

import net.horsttnann.Dialog.R;
import Android.app.Activity;
import Android.app.ProgressDialog;
import Android.os.Bundle;
import Android.view.View;

public class DialogActivity extends Activity {
    ProgressDialog progressDialog;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void onClick2(View v) {
        // ---show the dialog---
        final ProgressDialog dialog = ProgressDialog.show(this,
                "Doing something", "Please wait...", true);
        new Thread(new Runnable() {
            public void run() {
                try {
                    // ---simulate doing something lengthy---
                    Thread.sleep(5000);
                    // ---dismiss the dialog---
                    dialog.dismiss();
                } catch (interruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}  www.atcpu.com

4、按F11调试,点击按钮,弹出“进度条”对话框。

  


基本上,想要创建一个“进度条”对话框,只需要创建一个ProgressDialog类的实例,然后调用show()方法:

// ---show the dialog---
final ProgressDialog dialog = ProgressDialog.show(this,
        "Doing something", "Please wait...", true);
因为它是一个“模态”的对话框,所以它就会把其他UI组件给遮盖住,直到它被解除。如果想要在后台执行一个“长期运行”的任务,可以创建一个线程。run()方法里面的代码将会在一个独立的线程里面执行。下面的代码使用sleep()方法,模拟了一个需要5秒执行的后台任务:new Thread(new Runnable() {
    public void run() {
        try {
            // ---simulate doing something lengthy---
            Thread.sleep(5000);
            // ---dismiss the dialog---
            dialog.dismiss();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}).start();
5秒钟之后,执行dismiss()方法,对话框就被解除了。

摘自 manoel的专栏

喜欢0 评分0
游客

返回顶部