在很多PC软件或手机软件中,我们都会看见 “加载中...” 类似的对话框,当然,在android应用程序中也是如此。如果我们想在android应用程序中使用这样的效果,那么就需要用到ProgressDialog。首先,我们来看一下ProgressDialog这个类。
ProgressDialog类继承自AlertDialog类,同样存放在android.app包中。ProgressDialog有两种形式,一种是圆圈旋转形式,一种是水平进度条形式,选择哪种形式可以通过以下两个属性值来设定:
static int | STYLE_HORIZONTAL Creates a ProgressDialog with a horizontal progress bar. |
static int | STYLE_SPINNER Creates a ProgressDialog with a ciruclar, spinning progress bar. |
注意,当设置为水平进度条形式时,进度的取值范围为0—10000。
ProgressDialog的构造方法有以下两种:
ProgressDialog(Context context) |
ProgressDialog(Context context, int theme) |
除了构造方法外,ProgressDialog还提供的如下的静态方法返回ProgressDialog对象:
static ProgressDialog | show(Context context, CharSequence title, CharSequence message) |
static ProgressDialog | show(Context context, CharSequence title, CharSequence message, boolean indeterminate) |
static ProgressDialog | show(Context context, CharSequence title, CharSequence message, boolean indeterminate, boolean cancelable) |
static ProgressDialog | show(Context context, CharSequence title, CharSequence message, boolean indeterminate, boolean cancelable, DialogInterface.OnCancelListener cancelListener) |
需要留意的是第一个参数必须是目前运行的Activity的Context。
android的ProgressDialog必须要在后台程序运行完毕前,以dismiss()方法来关闭取得焦点的对话框,否则程序就会陷入无法终止的无穷循环中。在线程中,不得有任何更改Context或parent View的任何状态,文字输出等时间,因为线程里的Context与View并不属于parent,两者之间也没有关联。
我们以下面一个简单的程序来学习ProgressDialog的应用:
public class MainActivity extends Activity
{
private Button button=null;
public ProgressDialog dialog=null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_main);
this.button=(Button)super.findViewById(R.id.button);
this.button.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
final CharSequence strDialogTitle=MainActivity.this.getString(R.string.str_dialog_title);
final CharSequence strDialogBody=MainActivity.this.getString(R.string.str_dialog_body);
//显示Progress对话框
dialog=ProgressDialog.show(MainActivity.this,strDialogTitle,strDialogBody,true);
new Thread()
{
@Override
public void run()
{
try
{
//表示后台运行的代码段,以暂停3秒代替
sleep(3000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
//卸载dialog对象
dialog.dismiss();
}
}
}.start();
}
});
}
}
该程序布局管理器仅需一个Button组件(id为button)即可,此处不再给出。
注意,为了代码更加符合规范,本程序在strings.xml中定义了如下字符串资源:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">demo2</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="execute">执行</string>
<string name="str_dialog_title">请稍等片刻</string>
<string name="str_dialog_body">正在执行...</string>
</resources>
程序运行效果截图: