万能的dialog封装

采用Builder设计模式,打造一个万能的dialog,使用时一句话调用不用再写一大串代码

框架图.png

一、搭建框架

创建五个对象类

1.AlertDialog ---- Builder创建
public class AlertDialog extends Dialog {
public AlertDialog(Context context, int themeResId) {
    super(context, themeResId);
}
public static class Builder{
}
}
2.AlertController ----AlertParams创建
 class AlertController {
  public AlertController(AlertDialog alertDialog, Window window) {
 }
 public static class AlertParams{
}  
}
3.DialogViewHelper 创建
 public class DialogViewHelper {
public DialogViewHelper(Context context, int layoutResId) {
  }
}
4.AlertDialog -----Builder

AlertDialog 构造:

  private AlertController mAlert;
  public AlertDialog(Context context, int themeResId) {
    super(context, themeResId);
    mAlert=new AlertController(this,getWindow());
    }

Builder 构造:

    private final AlertController.AlertParams P;
     /**
     * Creates a builder for an alert dialog that uses the default alert
     * dialog theme.
     * <p>
     * The default alert dialog theme is defined by
     * {@link android.R.attr#alertDialogTheme} within the parent
     * {@code context}'s theme.
     *
     * @param context the parent context
     */
    public Builder(Context context) {
        this(context,R.style.dialog);
    }


    /**
     * Creates a builder for an alert dialog that uses an explicit theme
     * resource.
     * <p>
     * The specified theme resource ({@code themeResId}) is applied on top
     * of the parent {@code context}'s theme. It may be specified as a
     * style resource containing a fully-populated theme, such as
     * {@link android.R.style#Theme_Material_Dialog}, to replace all
     * attributes in the parent {@code context}'s theme including primary
     * and accent colors.
     * <p>
     * To preserve attributes such as primary and accent colors, the
     * {@code themeResId} may instead be specified as an overlay theme such
     * as {@link android.R.style#ThemeOverlay_Material_Dialog}. This will
     * override only the window attributes necessary to style the alert
     * window as a dialog.
     * <p>
     * Alternatively, the {@code themeResId} may be specified as {@code 0}
     * to use the parent {@code context}'s resolved value for
     * {@link android.R.attr#alertDialogTheme}.
     *
     * @param context the parent context
     * @param themeResId the resource ID of the theme against which to inflate
     *                   this dialog, or {@code 0} to use the parent
     *                   {@code context}'s default alert dialog theme
     */
    public Builder(Context context, int themeResId) {
        P = new AlertController.AlertParams(context,themeResId);
    }

Builder的其他方法仿Dialog源码

    /**
     * Creates an {@link AlertDialog} with the arguments supplied to this
     * builder.
     * <p>
     * Calling this method does not display the dialog. If no additional
     * processing is needed, {@link #show()} may be called instead to both
     * create and display the dialog.
     */
    public AlertDialog create() {
        // Context has already been wrapped with the appropriate theme.
        final AlertDialog dialog = new AlertDialog(P.mContext,P.mThemeResId);
        P.apply(dialog.mAlert);
        dialog.setCancelable(P.mCancelable);
        if (P.mCancelable) {
            dialog.setCanceledOnTouchOutside(true);
        }
        dialog.setOnCancelListener(P.mOnCancelListener);
        dialog.setOnDismissListener(P.mOnDismissListener);
        if (P.mOnKeyListener != null) {
            dialog.setOnKeyListener(P.mOnKeyListener);
        }
        return dialog;
    }

    /**
     * Creates an {@link AlertDialog} with the arguments supplied to this
     * builder and immediately displays the dialog.
     * <p>
     * Calling this method is functionally identical to:
     * <pre>
     *     AlertDialog dialog = builder.create();
     *     dialog.show();
     * </pre>
     */
    public AlertDialog show() {
        final AlertDialog dialog = create();
        dialog.show();
        return dialog;
    }
    /**
     * Sets whether the dialog is cancelable or not.  Default is true.
     *
     * @return This Builder object to allow for chaining of calls to set   methods
     */
    public Builder setCancelable(boolean cancelable) {
        P.mCancelable = cancelable;
        return this;
    }

    /**
     * Sets the callback that will be called if the dialog is canceled.
     *
     * <p>Even in a cancelable dialog, the dialog may be dismissed for reasons other than
     * being canceled or one of the supplied choices being selected.
     * If you are interested in listening for all cases where the dialog is dismissed
     * and not just when it is canceled, see
     * {@link #setOnDismissListener(android.content.DialogInterface.OnDismissListener) setOnDismissListener}.</p>
     * @see #setCancelable(boolean)
     * @see #setOnDismissListener(android.content.DialogInterface.OnDismissListener)
     *
     * @return This Builder object to allow for chaining of calls to set methods
     */
    public Builder setOnCancelListener(OnCancelListener onCancelListener) {
        P.mOnCancelListener = onCancelListener;
        return this;
    }

    /**
     * Sets the callback that will be called when the dialog is dismissed         for any reason.
     *
     * @return This Builder object to allow for chaining of calls to set   methods
     */
    public Builder setOnDismissListener(OnDismissListener onDismissListener) {
        P.mOnDismissListener = onDismissListener;
        return this;
    }

    /**
     * Sets the callback that will be called if a key is dispatched to the dialog.
     *
     * @return This Builder object to allow for chaining of calls to set methods
     */
    public Builder setOnKeyListener(OnKeyListener onKeyListener) {
        P.mOnKeyListener = onKeyListener;
        return this;
    }

自定义一些方法:

     /**
     *设置布局内容的layoutId
     * @param layoutId
     * @return
     */
    public Builder setContentView(int layoutId) {
        P.mView = null;
        P.mViewLayoutResId = layoutId;
        return this;
    }

     /**
     * 设置文本
     * @param viewId
     * @param text
     * @return
     */
      public Builder setText(int viewId,CharSequence text){
         P.textArray.put(viewId,text);
        return this;

      }
/**
     * 设置点击事件
     * @param view
     * @param listener
     * @return
     */
    public Builder setOnClickListener(int view,View.OnClickListener listener){
        P.mClickArray.put(view,listener);
        return this;
    }

    /**
     * 设置全屏
      * @return
     */
    public Builder fullWidth(){
        P.mWidth= ViewGroup.LayoutParams.MATCH_PARENT;
        return this;

    }


    /**
     * 设置底部弹出
     * @return
     */
    public Builder fromBottom(boolean isAnimation){
        if (isAnimation){
           P.mAnimation=R.style.dialog_from_bottom_anim;
        }
        P.mGravity= Gravity.BOTTOM;
        return this;

    }

    /**
     * 设置宽 高
     * @return
     */
    public Builder setWidthAndHeight(int width,int height){
        P.mWidth=width;
        P.mHeight=height;
        return this;

    }

    /**
     * 设置默认 动画
     * @return
     */
    public Builder addDefaultAnimation(){
        P.mAnimation=R.style.dialog_scale_anim;
        return this;
    }

    /**
     * 设置动画
     * @param styleAnimation
     * @return
     */
    public Builder setAnimation(int styleAnimation){
        P.mAnimation=styleAnimation;
        return this;
    }

基本实现这些方法

5.AlertController ----AlertParams

AlertController 构建;

  private AlertDialog mDialog;
  private Window mWindow;
   private DialogViewHelper mViewHelper;
  public AlertController(AlertDialog alertDialog, Window window) {
       this.mDialog=alertDialog;
       this.mWindow=window;
 }
 public void setViewHelper(DialogViewHelper viewHelper){
    this.mViewHelper=viewHelper;
 }
/**
 * 获取Dialog
 * @return
 */
public AlertDialog getmDialog() {
    return mDialog;
}


/**
 * 设置文本
 * @param viewId
 * @param text
 */
public void setText(int viewId, CharSequence text) {
    mViewHelper.setText(viewId,text);
}

public  <T extends View> T getView(int viewId) {
    return mViewHelper.getView(viewId);
}

/**
 * 设置点击事件
 * @param viewId
 * @param listener
 */
public void setOnclickListener(int viewId, View.OnClickListener listener) {
    mViewHelper.setOnclickListener(viewId,listener);
}



/**
 * 获取Dialog的Window
 * @return
 */
public Window getmWindow() {
    return mWindow;
}

AlertParams 构建:

     public Context mContext;
     public int mThemeResId;
    //点击空白是否能够取消
    public boolean mCancelable=true;
    //dialog cancel监听
    public DialogInterface.OnCancelListener mOnCancelListener;
    //dialog Dismiss监听
    public DialogInterface.OnDismissListener mOnDismissListener;
    //dialog Key监听
    public DialogInterface.OnKeyListener mOnKeyListener;
    //布局View
    public View mView;
    //布局LayoutId
    public int mViewLayoutResId;
    //存放字体的修改
    public SparseArray<CharSequence> textArray=new SparseArray<>();
    //存放点击事件
    public SparseArray<View.OnClickListener> mClickArray=new SparseArray<>();
    public int mWidth= ViewGroup.LayoutParams.WRAP_CONTENT;
    //动画
    public int mAnimation=0;
    //位置
    public int mGravity= Gravity.BOTTOM;
    //设置高度
    public int mHeight=ViewGroup.LayoutParams.WRAP_CONTENT;

    public AlertParams(Context context, int themeResId) {
        this.mContext=context;
        this.mThemeResId=themeResId;

    }

    /**
     *绑定和设置参数
     * @param mAlert
     */
    public void apply(AlertController mAlert) {

        //1.设置布局
        DialogViewHelper viewHelper=null;
        if(mViewLayoutResId!= 0){
              viewHelper=new DialogViewHelper(mContext,mViewLayoutResId);
        }

        if (mView!=null){
            viewHelper=new DialogViewHelper();
            viewHelper.setContentView(mView);

        }
        if (viewHelper==null){
            throw new IllegalArgumentException("请设置布局setContentView");
        }
        //给Dialog设置布局
       mAlert.getmDialog().setContentView(viewHelper.getContentView());

        mAlert.setViewHelper(viewHelper);
        //2.设置文本
        int textArraySize = textArray.size();
        for (int i = 0; i <textArraySize; i++) {
            mAlert.setText(textArray.keyAt(i),textArray.valueAt(i));
        }

        //3.设置点击
        int clickArraySize = mClickArray.size();
        for (int i = 0; i <clickArraySize; i++) {
            mAlert.setOnclickListener(mClickArray.keyAt(i), mClickArray.valueAt(i));
        }



        //4.配置自定义的效果 全屏 从底部弹出 默认动画
        Window window=mAlert.getmWindow();
        //设置动画
        window.setGravity(mGravity);

        if (mAnimation!=0){
            window.setWindowAnimations(mAnimation);
        }

        //设置宽高
        WindowManager.LayoutParams params = window.getAttributes();
        params.width=mWidth;
        params.height=mHeight;
        window.setAttributes(params);
    }

DialogViewHelper 辅助类:

 private View mContentView=null;
 private SparseArray<WeakReference<View>> mView;
  public DialogViewHelper(Context context, int layoutResId) {
    this();
    mContentView= LayoutInflater.from(context).inflate(layoutResId,null);
   }
  public DialogViewHelper() {
    mView=new SparseArray<>();
   }
/**
 * 设置布局
 * @param contentView
 */
public void setContentView(View contentView) {
    this.mContentView = contentView;
}

/**
 * 设置文本
 * @param viewId
 * @param text
 */
public void setText(int viewId, CharSequence text) {
    //每次都findViewById 减少findViewById的次数
    TextView tv=getView(viewId);
  //        TextView tv= (TextView) mContentView.findViewById(viewId);
    if (tv!=null){
        tv.setText(text);
    }
}

public  <T extends View> T getView(int viewId) {

    WeakReference<View> viewWeakReference = mView.get(viewId);
    View view=null;
    if (viewWeakReference!=null){
        view= viewWeakReference.get();
    }
    if (view==null){
        view=  mContentView.findViewById(viewId);
        if (view!=null){
            mView.put(viewId,new WeakReference<>(view));
        }

    }
    return (T) view;
}

/**
 * 设置点击事件
 * @param viewId
 * @param listener
 */
public void setOnclickListener(int viewId, View.OnClickListener listener) {
    View view=getView(viewId);
    if (view!=null){
        view.setOnClickListener(listener);
    }
}

/**
 * 获取mContentView
 * @return
 */
public View getContentView() {
    return mContentView;
}

二、使用

            AlertDialog dialog= new AlertDialog.Builder(MainActivity.this)
                    .setContentView(R.layout.detail_comment_dialog)
                    .setText(R.id.submit_btn, "发送")
                    .fullWidth().show();

             final EditText editText = dialog.getView(R.id.comment_editor);

             dialog.setOnclickListener(R.id.submit_btn, new               View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(MainActivity.this,editText.getText().toString(),Toast.LENGTH_SHORT).show();
                }
            });

三、扩展

宽展只需要在Builder中写相应方法,AlertParams中设置就ok

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,539评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,911评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,337评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,723评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,795评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,762评论 1 294
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,742评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,508评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,954评论 1 308
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,247评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,404评论 1 345
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,104评论 5 340
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,736评论 3 324
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,352评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,557评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,371评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,292评论 2 352

推荐阅读更多精彩内容