AlertDialog源码解析

        AlertDialog是我们平时使用很多de空间。那么,这个控件是怎么实现的呢?AlertDialog继承自Dialog,实现了很多扩展功能。首先,我们先来看一下AlertDialog类的构造器。

protected AlertDialog(Context context) {
        this(context, resolveDialogTheme(context, 0), true);
    }
 
    /**
     * Construct an AlertDialog that uses an explicit theme.  The actual style
     * that an AlertDialog uses is a private implementation, however you can
     * here supply either the name of an attribute in the theme from which
     * to get the dialog's style (such as {@link android.R.attr#alertDialogTheme}
     * or one of the constants {@link #THEME_TRADITIONAL},
     * {@link #THEME_HOLO_DARK}, or {@link #THEME_HOLO_LIGHT}.
     */
    protected AlertDialog(Context context, int theme) {
        this(context, theme, true);
    }
 
    AlertDialog(Context context, int theme, boolean createThemeContextWrapper) {
        super(context, resolveDialogTheme(context, theme), createThemeContextWrapper);
 
        mWindow.alwaysReadCloseOnTouchAttr();
        mAlert = new AlertController(getContext(), this, getWindow());
    }
 
    protected AlertDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, resolveDialogTheme(context, 0));
        mWindow.alwaysReadCloseOnTouchAttr();
        setCancelable(cancelable);
        setOnCancelListener(cancelListener);
        mAlert = new AlertController(context, this, getWindow());
    }

可以看见,这个类的构造器通过protected修饰。因此,我们不能直接new一个AlertDialog。可以看见,在构造函数中,我们new了一个AlertController类,这个类是用于实现主要逻辑的。那么,我们怎么创建一个AlertDialog类呢?原来,在AlertDialog中有一个静态内部类Builder,我们设置属性等功能都是通过这个类实现的。

public static class Builder {
        private final AlertController.AlertParams P;
        private int mTheme;
        
        /**
         * Constructor using a context for this builder and the {@link AlertDialog} it creates.
         */
        public Builder(Context context) {
            this(context, resolveDialogTheme(context, 0));
        }
 
        /**
         * Constructor using a context and theme for this builder and
         * the {@link AlertDialo
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值