본문 바로가기
프로그래밍/Android

[Android] Dialog 중복생성 방지

by Youngs_ 2023. 4. 14.

 

현재 해당 방법은 Deprecate 되었다! 가급적이면 다른 방법을 사용하는게 나을듯

 

Dialog를 생성할 때, 아래와 같이 AlertDialog 클래스를 이용하여 많이 생성한다.

 AlertDialog.Builder dialog = new AlertDialog.Builder(this);

        dialog.setMessage("message:);

        dialog.setView(view);

        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            @Override

            public void onClick(DialogInterface dialog, int button) {

                dialog.dismiss();

                finish();

            }

        });

        dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override

            public void onClick(DialogInterface dialog, int button) {

//Something do it

            }

        });

        dialog.setOnCancelListener(new OnCancelListener() {

            @Override

            public void onCancel(DialogInterface dialog) {

                dialog.dismiss();

                finish();

            }

        });

dialog.show();

 

 만약 위 함수 호출을 OnResume이나 Button에서 onClickListener로 중복 호출을 할 경우!!

Dialog 가 중복으로 실행 되는 것을 확인 할 수 있을 것이다.

 

이럴 경우를 대비해서 직접 Flag를 주거나 Dialog가 null인지 체크하여 문제를 해결을 하지만,

그보다 더 쉽게 onCreateDialog 함수를 사용하면 중복 문제는 금방 풀린다.

 

생성된 Dialog를 onCreateDialog로 넘기면 중복 실행을 하지 않고 유지 시켜준다.

사용법은 간단한다.

Activity에서 onCreateDialog를 overriding 하여 Dialog를 생성하고 넘겨주기만 하면된다.

private static final int DIALOG_ID = 1;



@Override

    protected Dialog onCreateDialog(int id, Bundle bundle) {

        switch (id) {

            case DIALOG_ID:

                return 생성된 Dialog;

            default:

                return super.onCreateDialog(id, bundle);

        }

    }

 

OnCreateDialog 함수는 showDialog(DIALOG_ID); 를 호출 하게 되면 callback되는 함수이다.

이 외적으로 onPrepareDialog라는 함수가 있는데 생성된 Dialog를 Update 할 때 사용됩니다.

 


출처 : https://gogorchg.tistory.com/entry/Android-Dialog-%EC%A4%91%EB%B3%B5-%EB%B0%A9%EC%A7%80

 

[Android] Dialog 중복 방지

Dialog를 생성할 때, 아래와 같이 AlertDialog 클래스를 이용하여 많이 생성한다. AlertDialog.Builder dialog = new AlertDialog.Builder(this); dialog.setMessage("message:); dialog.setView(view); dialog.setNegativeButton("Cancel", new Dial

gogorchg.tistory.com

 

댓글