android.os.AlertDialog 是 Android API中提供的一个对话框类。我们可以非常容易的在我们的应用中使用类。
AlertDialog UI 基本界面
AlertDialog 界面展现
一,怎样使用AlertDialog?
Alert Dialog 是和Activity组件一起使用的。Activity提供了一个函数
protected Dialog onCreateDialog(int id, Bundle args)
这是一个回调(callback)函数,意味着我们不应该在程序代码中直接调用这个函数 。那么当什么时候系统会调用这个函数呢?
当我们第一次调用Activity的showDialog(int id) 函数时,系统会去调用 onCreateDialog 函数,在这个函数中 创建 id 参数
对应的dialog;
main.xml 代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:text="Basic Alert Dialog" android:id="@+id/BtnShowBasicAlertDialog" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
在主界面中加入一个按钮BtnShowBasicAlertDialog。
DialogActivity.java代码:
package mike.lei.shen;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class DialogActivity extends Activity
implements DialogInterface.OnClickListener,OnClickListener
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn1 = (Button)findViewById(R.id.BtnShowBasicAlertDialog);
//对R.id.BtnShowBasicAlertDialog设置事件处理函数
btn1.setOnClickListener(this);
}
//step1, define dialog IDs ,that will be used in showDialog function
static final int DIALOG_ID_HELLO = 0;
//step2 override onCreateDialog call-back function
@Override
protected Dialog onCreateDialog(int id, Bundle args) {
Dialog dialog;
switch(id)
{
//if there's a call to showDialog(DIALOG_ID_HELLO) first time,
//this case will be called.
case DIALOG_ID_HELLO:
//创建Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Hello Title"); //设置dialog标题
builder.setMessage("Hello,Alert Dialog!"); //设置需要显示的信息
builder.setIcon(R.drawable.icon); //设置图标
builder.setPositiveButton("OK", this); //设置一个button
dialog = builder.create(); //创建dialog
break;
default:
dialog = null;
}
return dialog;
//return super.onCreateDialog(id, args);
}
//Alert Dialog的事件处理函数
//this method will be called when a button in a dialog is clicked
public void onClick(DialogInterface dialog, int which) {
//关闭AlertDialog对话框
dismissDialog(DIALOG_ID_HELLO);
}
//Activity 界面上的Click事件
public void onClick(View v) {
switch(v.getId())
{
case R.id.BtnShowBasicAlertDialog:
{ //显示AlertDialog对话框
showDialog(DIALOG_ID_HELLO);
}
}
}
}
执行效果:
系统提供的AlertDialog类的主要界面元素有:
标题(title) : 示例中的 Hello Title AlertDialog.Builder.setTitle
图标(Icon): 图标 如上图中的上机器人图标 AlertDialog.Builder.setIcon
消息 (Message): 显示的具体消息 ”Hello , Alert Dialog" AlertDialog.Builder.setMessage
按钮: 显示OK信息 AlertDialog.Builder.setPositiveButton