dialog是android的对话框控件,包括:
- 警告对话框:AlertDialog
- 进度对话框:ProgressDialog
- 日期选择对话框:DatePickerDialog
- 时间选择对话框:TimePickerDialog
- 自定义对话框:从Dialog继承
通过AlertDialog,我们可以实现普通式、列表式及自定义等。下面给出两个典型例子:
- 普通式:
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setIcon(R.drawable.ic_launcher); //设置图标 builder.setTitle("错误提示"); //设置标题栏 builder.setMessage("数据库读取错误"); //对话框内容 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { //确认按键的事件触发 @Override public void onClick(DialogInterface dialog, int which) { Toast t = Toast.makeText(getApplicationContext(), "确定", Toast.LENGTH_LONG); t.show(); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){ //取消按键的事件触发 @Override public void onClick(DialogInterface dialog, int which) { Toast t = Toast.makeText(getApplicationContext(), "取消", Toast.LENGTH_LONG); t.show(); } }); builder.create().show();
- 自定义输入
- 定义一个layout
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" > <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="21dp" android:ems="10" /> <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText1" android:layout_below="@+id/editText1" android:layout_marginTop="15dp" android:ems="10" android:inputType="textPersonName" /> </RelativeLayout>
-
- 在构造时动态生成视图,如下:
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); final View view = inflater.inflate(R.layout.dialog_input, null); builder.setIcon(R.drawable.ic_launcher); builder.setTitle("输入框"); builder.setView(view);
时间: 2024-12-15 01:51:56