Android对话框
Android对话框 Dialog,其直接子类 AlertDialog. AlertDialog的直接子类: DatePickerDialog、TimePickerDialog、ProgressDialog
对话框和菜单一样,都是由Activity统一管理的,我们只需要重新实现onCreateDialog(int id)回调方法,根据showDialog(int id)传进来的不同对话框id,初始化并返回相应的对话框。
下面举一个功能简单的例子来说明 对话框的使用。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>
布局中仅仅引入一个TextView;
package com.example.dialog1;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
final int DIALOG_WELCOME=1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showDialog(DIALOG_WELCOME);
}
//初始化对话框,其参数id 为showDialog(DIALOG_WELCOME)传入。
protected Dialog onCreateDialog(int id){
switch(id){
case DIALOG_WELCOME:
//AlertDialog.Builder为静态类,使用它是因为 AlertDialog.Builder提供了一些更为方便的初始化对话框的方法
AlertDialog.Builder builder=new AlertDialog.Builder(this);
//setIcon 设置标题图标
builder.setIcon(android.R.drawable.ic_dialog_info);
builder.setTitle("欢迎");
builder.setMessage("欢迎使用本程序!");
//setPositiveButton设置对话框底部的按钮,这里传入一个监听器处理按钮单击事件。
return builder.setPositiveButton("确定",new OnClickListener(){
public void onClick(DialogInterface a0,int a1){
TextView tv=(TextView)findViewById(R.id.textview);
tv.setText("欢迎使用对话框:OK!");
}
}).create();
default:
return null;
}
}
}