原生对话框【Dialog】AlertDialog和.Builder

795730-20170214112751300-248824797.png

使用大全

public class MainActivity extends ListActivity {
    private List<String> mList;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        String[] array = { "普通Dialog""确定取消对话框 AlertDialog""单选对话框 AlertDialog""多选对话框 AlertDialog"//
                "自定义View的Dialog---注意:不同主题下显示效果大不相同""自定义View的AlertDialog---注意:不同主题下显示效果大不相同"//
                "自定义Dialog的位置""自定义AlertDialog的位置"//
                "进度条对话框 ProgressDialog""带进度的进度条对话框 ProgressDialog"};
        for (int i = 0; i < array.length; i++) {
            array[i] = i + "、" + array[i];
        }
        mList = new ArrayList<String>(Arrays.asList(array));
        setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1mList));
    }
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        switch (position) {
        case 0://普通Dialog
            showDialog(this);
            break;
        case 1://确定取消对话框 AlertDialog
            showSureOrCancleDialog(this);
            break;
        case 2://单选对话框 AlertDialog
            showSingleChoiceDialog(this);
            break;
        case 3://多选对话框 AlertDialog
            showMultiChoiceDialog(this);
            break;
        case 4://自定义View的Dialog---注意:不同主题下显示效果大不相同
            showCustomDialog(this);
            break;
        case 5://自定义View的AlertDialog---注意:不同主题下显示效果大不相同
            showCustomAlertDialog(this);
            break;
        case 6://自定义Dialog的位置
            showDialogAnyWhere(this);
            break;
        case 7://自定义AlertDialog的位置
            showAlertDialogAnyWhere(this);
            break;
        case 8://进度条对话框 ProgressDialog
            showSimpleProgressDialog(this);
            break;
        case 9://带进度的进度条对话框 ProgressDialog
            showProgressDialog(this);
            break;
        }
    }
    //Dialog,基本上没有什么API可用的***************************************************************************************************************
    public static void showDialog(Context context) {
        Dialog dialog = new Dialog(context);
        dialog.setTitle("基本上没有什么API可用的");
        dialog.show();
    }
    /**确定取消对话框,旋转屏幕后对话框消失*/
    public static void showSureOrCancleDialog(final Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle("标题").setMessage("内容")//
                .setCancelable(false)//点击返回键或对话框外部时是否消失,默认为true
                .setNegativeButton("取消"null)//
                .setPositiveButton("确定"new OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        //参数:dialog-The dialog that received the click.;which-The button that was clicked
                        Toast.makeText(context, "确定被点击了", Toast.LENGTH_SHORT).show();
                    }
                });
        builder.create().show();
    }
    /**单选对话框*/
    public static void showSingleChoiceDialog(final Context context) {
        final String[] items = { "男""女""未知" };
        AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle("请选择您的性别")//
                .setSingleChoiceItems(items, -1, new OnClickListener() {//第二个参数指定选择的是哪个,-1代表默认没有选中
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(context, "您的性别:" + items[which], Toast.LENGTH_SHORT).show();
                            }
                        }).setPositiveButton("确定"null).setNegativeButton("取消"null);
        builder.create().show();
    }
    /**多选对话框*/
    public static void showMultiChoiceDialog(final Context context) {
        final String[] items = { "苹果""梨""菠萝""香蕉""黄瓜" };
        final boolean[] result = new boolean[] { truefalsetruefalsefalse };//对应条目默认是否被选中
        AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle("请选择你最爱吃的水果")//
                .setMultiChoiceItems(items, result, new OnMultiChoiceClickListener() {
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        String inf = "";
                        if (isChecked) {
                            inf = " 被选中了";
                        } else {
                            inf = " 被取消选中了";
                        }
                        Toast.makeText(context, items[which] + inf, Toast.LENGTH_SHORT).show();
                        result[which] = isChecked;
                    }
                })//
                .setPositiveButton("提交"new OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        StringBuffer sb = new StringBuffer();
                        for (int i = 0; i < result.length; i++) {
                            if (result[i]) {
                                sb.append(items[i] + " ");
                            }
                        }
                        Toast.makeText(context, "您选中了:" + sb.toString(), Toast.LENGTH_SHORT).show();
                    }
                });
        builder.create().show();
    }
    //自定义View的Dialog。注意:不同主题下显示效果大不相同*********************************************************************************************
    public static void showCustomDialog(Context context) {
        Dialog dialog = new Dialog(context);
        dialog.setContentView(R.layout.layout_dialog);
        dialog.show();
    }
    public static void showCustomAlertDialog(Context context) {
        new AlertDialog.Builder(context).setView(R.layout.layout_dialog).create().show();
    }
    //自定义对话框显示位置**********************************************************************************************************************************
    public static void showDialogAnyWhere(Context context) {
        Dialog dialog = new Dialog(context);
        dialog.setContentView(R.layout.layout_dialog2);
        Window dialogWindow = dialog.getWindow()// 获取对话框窗口对象
        dialogWindow.setBackgroundDrawable(new ColorDrawable(0xffff0000));
        dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);//修改对话框的布局设置,和mLayoutParams.gravity属性的值一致
        WindowManager.LayoutParams mLayoutParams = dialogWindow.getAttributes();//获取对话框参数对象
        mLayoutParams.x = 0;// 表示相对于【原始位置】的偏移,当为Gravity.LEFT时就表示相对左边界的偏移,正值右移,负值忽略
        mLayoutParams.y = 20;//当为Gravity.BOTTOM时正值上移,负值忽略
        mLayoutParams.height = 900;//宽高设置是否有效也是和主题有关的
        mLayoutParams.alpha = 0.8f; // 透明度
        dialogWindow.setAttributes(mLayoutParams);
        dialog.show();
    }
    public static void showAlertDialogAnyWhere(Context context) {
        AlertDialog dialog = new AlertDialog.Builder(context).setView(R.layout.layout_dialog2).create();
        Window dialogWindow = dialog.getWindow()// 获取对话框窗口对象
        dialogWindow.setBackgroundDrawable(new ColorDrawable(0xffff0000));
        dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);//修改对话框的布局设置,和mLayoutParams.gravity属性的值一致
        WindowManager.LayoutParams mLayoutParams = dialogWindow.getAttributes();//获取对话框参数对象
        mLayoutParams.x = 0;// 表示相对于【原始位置】的偏移,当为Gravity.LEFT时就表示相对左边界的偏移,正值右移,负值忽略
        mLayoutParams.y = 20;//当为Gravity.BOTTOM时正值上移,负值忽略
        mLayoutParams.height = 900;//宽高设置是否有效也是和主题有关的
        mLayoutParams.alpha = 0.8f; // 透明度
        dialogWindow.setAttributes(mLayoutParams);
        dialog.show();
    }
    //进度条对话框ProgressDialog********************************************************************************************************************
    public static void showSimpleProgressDialog(Context context) {
        final ProgressDialog pd = new ProgressDialog(context);//不需要创建器
        pd.setTitle("提醒");
        pd.setMessage("正在加载数据,请稍等...");
        pd.setCancelable(false);
        pd.show();
        new Thread() {
            public void run() {
                SystemClock.sleep(2000);
                pd.dismiss();//可以在子进程中关闭进度条。
                //旋转屏幕后ProgressDialog被销毁了,而此线程会继续运行,当调用pd.dismiss()时由于pd为空,所以会导致异常。Activity直接挂掉!
            };
        }.start();
    }
    /**带进度的进度条对话框*/
    public static void showProgressDialog(final Context context) {
        final ProgressDialog pd = new ProgressDialog(context);
        pd.setTitle("提醒");
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);//当设置此属性的值后才会有进度显示
        pd.setMax(100);
        pd.setMessage("正在加载数据,请稍等...");
        pd.setCancelable(false);
        pd.show();
        new Thread() {
            public void run() {
                for (int i = 0; i < 100; i++) {
                    SystemClock.sleep(20);
                    pd.setProgress(i);//改变当前进度。可以在子线程中改变进度条的进度。
                }
                pd.dismiss();//当进度为100%时关闭对话框
                //仅为了演示Toast才这么搞!
                Looper.prepare();
                Toast.makeText(context, "加载完毕", Toast.LENGTH_SHORT).show();
                Looper.loop();
            };
        }.start();
    }
}

自定义Dialog的布局1

<?xml version="1.0" encoding="utf-8"?>
<!-- 注意:不同主题下显示效果大不相同 -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="180dp"
    android:layout_height="400dp"
    android:background="@android:color/holo_blue_light"
    android:gravity="center_horizontal"
    android:orientation="vertical" >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />
    <EditText
        android:id="@+id/et_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/et_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:inputType="textPassword" />
</LinearLayout>

自定义Dialog的布局2

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/holo_blue_light"
    android:gravity="center_horizontal"
    android:orientation="vertical" >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />
    <EditText
        android:id="@+id/et_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/et_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:inputType="textPassword" />
</LinearLayout>

Dialog相关API

public   class  Dialog  implements  DialogInterface, Window.Callback, KeyEvent.Callback, View.OnCreateContextMenuListener
  795730-20170214112752816-149434909.png   795730-20170214112753238-1412695983.png    795730-20170214112753707-1432345030.png
AlertDialog是Dialog的一个直接子类
public class AlertDialog extends Dialog implements android.content.DialogInterface
795730-20170214112754207-1299215702.png   
一个AlertDialog可以有两个以上的Button,可以对一个AlertDialog设置相应的信息,比如title、massage等等。
不能直接通过AlertDialog的构造函数来生产一个AlertDialog(AlertDialog所有的构造方法都是 protected), 只能通过 AlertDialog的静态内部类Builder 来创建。
public static class Builder
795730-20170214112754707-1652720733.png
相比 Dialog(基本没有什么set方法) ,AlertDialog使用起来相当方便,几行代码就可以搞定。

附件列表

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值