What is a DialogFragment

Is a pop-up Fragment that uses AlertDialog internally and has the same life cycle as a Fragment. However, the Dialog lifecycle has also been added

DialogFragment Life cycle

  • 1. OnAttach (Activity) : called when the Activity is associated with a Fragment (deprecated, but called anyway)

  • 2. OnAttach (Context) : called when an Activity is associated with a Fragment

  • 3. OnCreate (Bundle) : Initialize the Fragment. The previously saved value can be obtained with the savedInstanceState parameter

  • OnCreateDialog (Bundle) : Rewrite to generate its own dialogs, usually used to display alertDialogs instead of regular dialogs; You don’t need to implement OnCreateView to do this, because the AlertDialog handles its own content.

  • 5. OnCreateView (LayoutInflater, ViewGroup, Bundle) : Let the Fragment instantiate the View.

  • OnViewCreated (View, Bundle) : Immediately following the onCreateView call, the View is initialized.

  • 7. OnActivityCreated (Bundle) : When this method is executed, the onCreate method of the Activity bound to the Fragment has been executed and returned. UI operations that interact with the Activity can be performed in this method. Therefore, the onCreate method of the Activity is not completed before the method is executed. Raises a null-pointer exception.

  • 8. OnStart () : The Fragment changes from invisible to visible when executing this method.

  • 9. OnResume () : When this method is executed, the Fragment is active and the user can interact with it.

  • 10. OnCancel (DialogInterface) : This method is called when the dialog box is cancelled. OnDismiss is going to call onDismiss

  • 11. OnDismiss (DialogInterface) : This method is called when the dialog box is closed.

  • 12. OnPause () : When this method is executed, the Fragment is paused but still visible and cannot be interacted with.

  • 13. OnStop () : The Fragment is completely invisible when this method is executed.

  • 14. OnDestroyView () : Destroys views associated with the Fragment, but without unbinding the view from the Activity, you can recreate the view using the onCreateView method. This method is usually called in ViewPager+Fragment mode.

  • 15. OnDestroy () : Fragment. This method is usually called when the Back key is pressed to exit or when the Fragment is reclaimed.

  • 16. OnDetach () : Unbind the Activity. Called after the onDestroy method.

Reprinted in: Nuggets

DialogFragment encapsulation

I did not write the background (shape), according to their own situation write oh

The effect picture after encapsulation :(the completion code will be given at the bottom of the article)

format rendering
Default effect:
Hide left button/external unclickable effect:
Bottom pop-up/external non-clickable/add animation effect:

Ideas:

In onCreateDialog, create an AlertDialog and pass the Dialog layout into the AlertDialog to use.

Dialog layout:

Just pass in the common layout and add it using any ViewGroup.

General flow chart:

InitRootView code flowchart:

Complete code:

/ * * *@ProjectName: My Application
 * @Package: com.example.myapplication.fragmentDialog
 * @ClassName: SwitchDialogFragment
 * @Author: szj
 * @CreateDate: 5/11/21 2:40 PM
 * @UpdateDate: 5/11/21 2:40 PM
 * @UpdateRemark: Updated description *@Version: 1.0 * /
public class SwitchDialogFragment extends DialogFragment implements View.OnClickListener {
    private final String title;
    private final Context mContext;
    private String rightName = "Closed", leftName = "Sure";

    //RootView width and height are adaptive by default
    private int rootViewWeight = ViewGroup.MarginLayoutParams.WRAP_CONTENT;
    private int rootViewHeight = ViewGroup.MarginLayoutParams.WRAP_CONTENT;

    // Whether the left/right buttons are displayed by default (true hidden)
    private boolean leftVisibility, rightVisibility;

    //Dialog to click outside to disappear (true to disappear)
    private boolean isDisappear;

    // Whether bottom popup (true bottom popup)
    private boolean isBottomShow;

    // Whether to display animation (true displays animation)
    private boolean isAnimation;

    // Public layout (constructor passed in)
    private final View view;

    / * * *@paramView middle public layout *@paramThe title title *@paramContext Context */
    public SwitchDialogFragment(View view, String title, Context context) {
        this.view = view;
        this.title = title;
        this.mContext = context;
    }


    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

        / / Dialog layout
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_layout, null.false);
        // Set Dialog layout width and height
        view.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        // Initialize the public layout
        initRootView(view);

        // Set a custom layout
        builder.setView(view);

        // Initialize the top title
        initTitle(view);

        // Initialize the bottom button operation
        initBtButton(view);

        AlertDialog alertDialog = builder.create();

        // Click to see if the outside disappearssetDialogCancelable(alertDialog, ! isDisappear);// Whether the Dialog is displayed at the bottom
        setDialogBottom(alertDialog, isBottomShow);

        // Set the Dialog animation
        setDialogAnimation(alertDialog, isAnimation);

        return alertDialog;
    }

    /** * Set Dialog Animation **@paramAlertDialog alertDialog object *@paramIsAnimation Whether to display animation true Displays animation */
    private void setDialogAnimation(AlertDialog alertDialog, boolean isAnimation) {
        if(isAnimation) { alertDialog.getWindow().getAttributes().windowAnimations = R.style.BottomToTopAnim; }}/** ** Dialog bottom popup **@paramAlertDialog Dialog object *@paramIsBottomShow true Bottom pops up (default false) */
    private void setDialogBottom(AlertDialog alertDialog, boolean isBottomShow) {
        if(isBottomShow) { Window dialogWindow = alertDialog.getWindow(); WindowManager.LayoutParams lp = dialogWindow.getAttributes(); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.WRAP_CONTENT; dialogWindow.setAttributes(lp); dialogWindow.setGravity(Gravity.BOTTOM); }}/** * Click outside to disappear **@paramAlertDialog alertDialog object *@paramIsDisappear True */
    private void setDialogCancelable(AlertDialog alertDialog, boolean isDisappear) {
        alertDialog.setCancelable(isDisappear);
        alertDialog.setCanceledOnTouchOutside(isDisappear);

        // The back key does not disappear
        alertDialog.setOnKeyListener((dialog, keyCode, event) -> keyCode == KeyEvent.KEYCODE_BACK);
    }

    / / the View at the top
    private void initTitle(View view) {
        TextView tv_data = view.findViewById(R.id.tv_data);
        tv_data.setText(title);
    }

    private void initRootView(View view1) {
        //Dialog public layout
        RelativeLayout root = view1.findViewById(R.id.rootView);
        root.setLayoutParams(new LinearLayout.LayoutParams(rootViewWeight, rootViewHeight));
        // Add the public layout to the Dialog
        root.addView(this.view);
    }

    // Set RootView width and height
    public void setRootViewLayoutParams(int weight, int height) {
        rootViewWeight = weight;
        rootViewHeight = height;
    }

    /** * The left button name */
    public void setLeftName(String name) {
        leftName = name;
    }

    /** * Whether the left button displays **@paramIsVisibility true Hide */
    public void setLeftVisibility(boolean isVisibility) {
        leftVisibility = isVisibility;
    }

    /** * The left button name */
    public void setRightName(String name) {
        rightName = name;
    }

    /** * Whether the side button displays **@paramIsVisibility true Hide */
    public void setRightVisibility(boolean isVisibility) {
        rightVisibility = isVisibility;
    }

    /** * dialog click to see if the outside disappears **@paramIsDisappear True */
    public void setDisappear(boolean isDisappear) {
        this.isDisappear = isDisappear;
    }

    /** * whether the bottom of the Dialog displays **@paramIsShow true Displays */ at the bottom
    public void setBottomShow(boolean isShow) {
        isBottomShow = isShow;
    }

    public void setDialogAnimation(boolean isAnimationShow) {
        isAnimation = isAnimationShow;
    }

    // Bottom button configuration
    private void initBtButton(View view) { Button bt_left = view.findViewById(R.id.bt_left); Button bt_right = view.findViewById(R.id.bt_right); bt_left.setText(leftName); bt_right.setText(rightName); bt_left.setVisibility(! leftVisibility ? View.VISIBLE : View.GONE); bt_right.setVisibility(! rightVisibility ? View.VISIBLE : View.GONE); bt_left.setOnClickListener(this);
        bt_right.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.bt_left) {
            if(monDialogClick ! =null) {
                monDialogClick.onClone();
            }
            dismiss();
        } else if (id == R.id.bt_right) {
            if(monDialogClick ! =null) { monDialogClick.onSuccess(); } dismiss(); }}public interface onDialogClick {
        void onSuccess(a);

        void onClone(a);
    }

    public onDialogClick monDialogClick;

    public void setOnDialogClick(onDialogClick monDialogClick) {
        this.monDialogClick = monDialogClick; }}Copy the code

DialogFragment used animation:

R.styles.BottomToTopAnim:

<style name="BottomToTopAnim" parent="android:Animation">
        <item name="android:windowEnterAnimation">@anim/dialog_alpha_show</item>
        <item name="android:windowExitAnimation">@anim/dialog_alpha_hide</item>
 </style>
Copy the code

R.anim.dialog_alpha.show.xml


      
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300">
    <translate
        android:fromYDelta="100%"
        android:toYDelta="0%" />

    <alpha
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />
</set>
Copy the code

R.anim.dialog_alpha.hide.xml


      
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromYDelta="0%p"
        android:toYDelta="100%p" />

    <alpha
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromAlpha="1.0"
        android:toAlpha="0.3" />
</set>
Copy the code

Use (kotlin) :

fun onDialogClick(view: View) {
        val view = LayoutInflater.from(this).inflate(R.layout.dialog_item, null.false)

        val dialog = SwitchDialogFragment(view, "Remind".this)

        dialog.show(supportFragmentManager, dialog.tag)


        / / RootView high wide
        dialog.setRootViewLayoutParams(ViewGroup.MarginLayoutParams.MATCH_PARENT, 300)

        // Left/right name
        dialog.setLeftName("NO")
        dialog.setRightName("YES")

// // The button on the left is hidden
        dialog.setLeftVisibility(true)

        // Click to see if the outside disappears
        dialog.setDisappear(true)

        // Bottom pops up
        dialog.setBottomShow(true)

        // Display animation
        dialog.setDialogAnimation(true)

        // Button click event callback
        dialog.setOnDialogClick(object : SwitchDialogFragment.onDialogClick {
            // Right button
            override fun onSuccess(a) {
                Toast.makeText(this@MainActivity."Right button", Toast.LENGTH_SHORT).show()
            }

            // Left button
            override fun onClone(a) {
                Toast.makeText(this@MainActivity."Left button", Toast.LENGTH_SHORT).show()
            }
        })
    }
Copy the code

The complete code

Original is not easy, your praise is the biggest help to me ~