亳州幼师学校录取分:Android开发笔记(九) — ProgressDialog的应用

来源:百度文库 编辑:中财网 时间:2024/04/20 17:22:49

经常可以看见程序加载中的对话框,一般在程序运行前加载数据可以使用ProgressDialog对话框,这个类封装在Android.app.ProgressDialog里,当后台程序运行完毕,需要用dismiss()方法来关闭取得焦点,不然则永远不能关闭ProgressDialog对话框。我将做一个演示ProgressDialog的用法。
此例思路:
1、先在布局上面加一个Button,加入OnClickListener。
2、把ProgressDislog声明成全局的,在Button的OnClickListener中创建出来,我们使用的方法是show(Contextcontext, CharSequence title, CharSequence message, booleanindeterminate),来显示出ProgressDialog。第一个参数必须为目前运行Activity的Context,第二个参数是标题,第三个参数是内容,最后一个参数可传可不传。
3、在Button的OnClickListener中创建一个线程,让线程run的时候sleep三秒,然后使用dismiss()方法关闭刚才打开的ProgressDislog。

源程序如下:

Java语言: EX03_1801 package dan.ex03_18;
02
03 import android.app.Activity;
04 import android.app.ProgressDialog;
05 import android.os.Bundle;
06 import android.view.View;
07 import android.view.View.OnClickListener;
08 import android.widget.Button;
09 import android.widget.TextView;
10
11 public class EX03_18 extends Activity {
12     /** Called when the activity is first created. */
13     Button b ;
14     TextView t;
15     ProgressDialog pd;
16     @Override
17     public void onCreate(Bundle savedInstanceState) {
18         super.onCreate(savedInstanceState);
19         setContentView(R.layout.main);
20         b = (Button) findViewById(R.id.button);
21         t = (TextView) findViewById(R.id.text);
22        
23         b.setOnClickListener(myListener);
24     }
25    
26     OnClickListener myListener = new Button.OnClickListener(){
27
28         @Override
29         public void onClick(View v) {
30             // TODO Auto-generated method stub
31             pd = ProgressDialog.show(EX03_18.this, "标题", "内容",true);
32            
33             new Thread(){
34
35                 @Override
36                 public void run() {
37                     // TODO Auto-generated method stub
38                     try {
39                         sleep(3000);
40                     } catch (InterruptedException e) {
41                         // TODO Auto-generated catch block
42                         e.printStackTrace();
43                     }finally{
44                         pd.dismiss();
45                     }
46                 }
47                
48             }.start();
49         }
50        
51     };
52 }

 

布局文件:

XML语言: main.xml01
02 03 android:id="@+id/main"
04 android:layout_width="fill_parent"
05 android:layout_height="fill_parent"
06 xmlns:android="http://schemas.android.com/apk/res/android"
07 >
08 09 android:id="@+id/text"
10 android:layout_width="wrap_content"
11 android:layout_height="wrap_content"
12 android:text="存数据之前"
13 android:layout_x="117px"
14 android:layout_y="68px"
15 >
16
17 18 android:id="@+id/button"
19 android:layout_width="wrap_content"
20 android:layout_height="wrap_content"
21 android:text="开始运算"
22 android:textSize="20sp"
23 android:layout_x="118px"
24 android:layout_y="181px"
25 >
26
27

 

运行效果: