About the title

Ah, this damned title, and everyone cheated in, think is tall, in fact, just a small package, big guys don’t spray.

EverythingDialogFragment

With the increase of business, a variety of dialog styles need to be realized. Traditionally, a variety of dialogs need to be written. On the one hand, it is difficult to maintain, and on the other hand, in multi-person development, everyone will write different dialogs, resulting in poor code reuse. Self-defined DialogFragment is a base class, by personal experience and ability, there are still deficiencies in the code, but also please big men more advice.

About the name

I originally wanted to choose a Basic edialogfragment, but the name was too common, so I had to choose a fancy name, but not too high profile, but not lose the connotation. Then I Google translated a lot of words, and finally found Everything, ha ha, everyone, don’t insult me.

public class EverythingDialogFragment extends DialogFragment {

  private View mRootView;
    private Dialog mDialog;
    private Context mContext;
    private float widthPercentSize;
    private float heightPercentSize;
    private int layoutResID;
    private EverythingDialogHolder holder;
    private int[] viewIds;
    private int theme;
    private boolean cancel;
    private boolean touchOutside;
    private int animations;

    public static EverythingDialogFragment newInstance() {
        EverythingDialogFragment fragment = new EverythingDialogFragment();
        return fragment;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mDialog = getDialog();
        if (mDialog != null) {
            try {
                mDialog.setOnDismissListener(null);
                mDialog.setOnCancelListener(null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (theme != 0){
            setStyle(DialogFragment.STYLE_NORMAL, theme);
        }
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mRootView==null){
            mRootView = inflater.inflate(layoutResID, container, false);
            setDialogSize(widthPercentSize, heightPercentSize);
        }
        return mRootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mDialog = getDialog();
       
        holder = EverythingDialogHolder.create(mRootView,this);
        if (viewConvertListener!=null){
            viewConvertListener.convertView(holder,this);
        }
        if (holder!=null && viewIds!=null && viewIds.length>0){
            holder.addChildClickListener(viewIds);
        }

        if (mDialog != null) {
            mDialog.setCanceledOnTouchOutside(touchOutside);
            mDialog.setOnKeyListener((dialog, keyCode, event) -> cancel);
            Window window = mDialog.getWindow();
            window.setWindowAnimations(animations);
        }
    }

    /**
     * 其他区域是否点击消失
     * @param touchOutside
     * @return
     */
    public EverythingDialogFragment setCanceledOnTouchOutside(boolean touchOutside){
        this.touchOutside=touchOutside;
        return this;
    }


    public EverythingDialogFragment setWindowAnimations(@StyleRes int resId) {
      this.animations=resId;
      return this;
    }

    /**
     * 屏蔽返回键
     * @param cancel
     * @return
     */
    public EverythingDialogFragment setCanceledOnTouch(boolean cancel){
        this.cancel=cancel;
        return this;
    }

    /**
     * 设置Style
     * @param theme
     * @return
     */
    public EverythingDialogFragment setStyle(int theme){
        this.theme=theme;
        return this;
    }

    /**
     * 设置布局
     * @param layoutResID
     * @return
     */
    public EverythingDialogFragment setContentView(@LayoutRes int layoutResID) {
        this.layoutResID = layoutResID;
        return this;
    }

    /**
     * 设置显示的宽
     * @param widthPercentSize
     * @return
     */
    public EverythingDialogFragment setWidthPercentSize(float widthPercentSize) {
        this.widthPercentSize = widthPercentSize;
        return this;
    }

    /**
     * 显示高
     * @param heightPercentSize
     * @return
     */
    public EverythingDialogFragment setHeightPercentSize(float heightPercentSize) {
        this.heightPercentSize = heightPercentSize;
        return this;
    }

    private void setFragmentManager(FragmentManager manager) {
        try {
            manager.beginTransaction().remove(this).commitAllowingStateLoss();
            super.show(manager, getClass().getSimpleName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public EverythingDialogFragment show(Object obj){
        if (obj!=null){
            if (obj instanceof FragmentActivity){
                FragmentActivity activity = (FragmentActivity) obj;
                setFragmentManager(activity.getSupportFragmentManager());
            }else if (obj instanceof Fragment){
                Fragment fragment = (Fragment) obj;
                setFragmentManager(fragment.getFragmentManager());
            }else {
                throw new IllegalArgumentException("not is FragmentManager");
            }
        }
        return this;
    }


    /**
     * 设置显示屏幕大小
     */
    private void setDialogSize(float widthPercent, float heightPercent) {
        DisplayMetrics dm = new DisplayMetrics();
        FragmentActivity activity = getActivity();
        Dialog dialog = getDialog();
        if (activity != null && dialog != null) {
            activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
            Window window = dialog.getWindow();
            if (window != null) {
                window.getDecorView().setPadding(0, 0, 0, 0);
                WindowManager.LayoutParams lp = window.getAttributes();

                lp.width = widthPercent == 0 ?
                        WindowManager.LayoutParams.WRAP_CONTENT : widthPercent == 1 ?
                        WindowManager.LayoutParams.MATCH_PARENT : (int) (dm.widthPixels * widthPercent);

                lp.height = heightPercent == 0 ?
                        WindowManager.LayoutParams.WRAP_CONTENT : heightPercent == 1 ?
                        WindowManager.LayoutParams.MATCH_PARENT : (int) (dm.heightPixels * heightPercent);

                window.setAttributes(lp);
                window.setBackgroundDrawable(new ColorDrawable());
            }
        }
    }


    /**
     * 可以暴露所有的view
     */
    public interface ConvertViewListener{
        void convertView(EverythingDialogHolder holder, final EverythingDialogFragment dialog);
    }

    private ConvertViewListener viewConvertListener;

    public EverythingDialogFragment setConvertViewListener(ConvertViewListener l){
        viewConvertListener=l;
        return this;
    }

    private OnChildClickListener childClickListener;

    public OnChildClickListener getOnChildClickListener() {
        return childClickListener;
    }


    /**
     * 设置子View Listener
     */
    public EverythingDialogFragment setOnChildClickListener(OnChildClickListener l, @IdRes final int ...viewIds){
        childClickListener=l;
        addIdRes(viewIds);
        return this;
    }

    /**
     * 设置子View Listener
     */
    public EverythingDialogFragment setOnChildClickListener(OnChildClickListener l){
        childClickListener=l;
        return this;
    }

    /**
     * 子view添加
     * @param viewIds
     * @return
     */
    public EverythingDialogFragment addIdRes(@IdRes final int ...viewIds){
        this.viewIds=viewIds;
        return this;
    }

}
Copy the code
public class EverythingDialogHolder { private final SparseArray<View> views; private final View convertView; private final LinkedHashSet<Integer> childClickViewIds; private final EverythingDialogFragment dialogFragment; public EverythingDialogHolder(View convertView, EverythingDialogFragment dialogFragment) { this.convertView = convertView; this.views = new SparseArray<>(); this.childClickViewIds =new LinkedHashSet<>(); this.dialogFragment=dialogFragment; } public static EverythingDialogHolder create(View view, EverythingDialogFragment dialogFragment) { return new EverythingDialogHolder(view,dialogFragment); } public <T extends View> T findViewById(@IdRes int viewId) { View view = views.get(viewId); if (view == null) { view = convertView.findViewById(viewId); views.put(viewId, view); } return (T) view; } /** * Add child View Listener * @param viewIds * @return */ public EverythingDialogHolder addChildClickListener int ... viewIds) { for (int viewId : viewIds) { childClickViewIds.add(viewId); final View view = findViewById(viewId); if (view ! = null) { if (! view.isClickable()) { view.setClickable(true); } view.setOnClickListener(v -> { if (dialogFragment ! =null && dialogFragment.getOnChildClickListener() ! = null){ dialogFragment.getOnChildClickListener().onChildViewClick(dialogFragment,v); }}); } } return this; }}Copy the code
public interface OnChildClickListener {
    void onChildViewClick(EverythingDialogFragment dialog, View v);
}

Copy the code

Usage (1)

EverythingDialogFragment. NewInstance (). SetWidthPercentSize (0.8 f) setHeightPercentSize (0.8 f). setContentView(R.layout.dialog_test). show(this). setConvertViewListener((holder, dialog) -> { TextView tv1 = holder.findViewById(R.id.tv1); });Copy the code

Method of use (2)

EverythingDialogFragment. NewInstance (). SetWidthPercentSize (0.8 f) setHeightPercentSize (0.8 f). setContentView(R.layout.dialog_test). addIdRes(R.id.tv1,R.id.tv2). show(this). setOnChildClickListener((dialog, v) -> { if (R.id.tv1 == v.getId()){ //do something } });Copy the code