진행 중인 경고 대화 상자가 닫히거나 취소되지 않음 (Alertdialog running ongoing dosen't dismiss or cancel)


문제 설명

진행 중인 경고 대화 상자가 닫히거나 취소되지 않음 (Alertdialog running ongoing dosen't dismiss or cancel)

answer에 따르면 다음 10개의 게시물이 로드될 때까지 대화 상자를 표시하고 싶습니다. 그래서 정적 alertDialog 메소드를 만들었습니다. 내 앱의 다른 위치에서 사용하지만 문제는 대화 상자가 취소되거나 해제되지 않는다는 것입니다.

setProgressDialog Utils 클래스에서

 public static AlertDialog setProgressDialog(Context context) {

        int llPadding = 30;
        LinearLayout ll = new LinearLayout(context);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        ll.setPadding(llPadding, llPadding, llPadding, llPadding);
        ll.setGravity(Gravity.CENTER);
        LinearLayout.LayoutParams llParam = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        llParam.gravity = Gravity.CENTER;
        ll.setLayoutParams(llParam);

        ProgressBar progressBar = new ProgressBar(context);
        progressBar.setIndeterminate(true);
        progressBar.setPadding(0, 0, llPadding, 0);
        progressBar.setLayoutParams(llParam);

        llParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        llParam.gravity = Gravity.CENTER;
        TextView tvText = new TextView(context);
        tvText.setText("Loading ...");
        tvText.setTextColor(context.getResources().getColor(R.color.black));
        tvText.setTextSize(20);
        tvText.setLayoutParams(llParam);

        ll.addView(progressBar);
        ll.addView(tvText);

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setCancelable(false);
        builder.setView(ll);

        AlertDialog dialog = builder.create();
        dialog.show();
        Window window = dialog.getWindow();
        if (window != null) {
            WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
            layoutParams.copyFrom(dialog.getWindow().getAttributes());
            layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
            layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
            dialog.getWindow().setAttributes(layoutParams);
        }
        return dialog;
    }

더 로드 버튼을 클릭할 때 HomeFragment에서 사용했습니다.

binding.loadMoreBtn.setOnClickListener(view ‑> {

            Utils.setProgressDialog(requireContext());

            if (Utils.hasNetworkAccess(requireContext())) {
                postViewModel.getPosts();
//                Log.w(TAG, "loadMoreBtn: "+dialog.isShowing() );
            } else {
                postViewModel.getAllItemsFromDataBase.getValue();
            }
            Utils.setProgressDialog(requireContext()).cancel();
            Utils.setProgressDialog(requireContext()).dismiss();

        });

추신: AlertDialog 대화 상자도 만들려고 했습니다. = 유틸리티.setProgressDialog(requireContext()); 대신 dialod.show() 메소드를 직접 호출하고 getPosts 후에 메소드를 취소하거나 해제하지만 dosen' 등장


참조 솔루션

방법 1:

binding.loadMoreBtn.setOnClickListener(view ‑> {

        Utils.setProgressDialog(requireContext());

        if (Utils.hasNetworkAccess(requireContext())) {
            postViewModel.getPosts(); //                Log.w(TAG, "loadMoreBtn: "+dialog.isShowing() );
        } else {
            postViewModel.getAllItemsFromDataBase.getValue();
        }
        Utils.setProgressDialog(requireContext()).cancel();
        Utils.setProgressDialog(requireContext()).dismiss();

    });

Here you invoked the static method Utils.setProgressDialog() multiple times; and each time it is called, it returns back a brand new dialog, so you'd dismiss a dialog that is not displayed on the screen.

Instead, you need to store the dialog that is returned from the first call to the method into a variable:

AlertDialog dialog = Utils.setProgressDialog(requireContext());

And then call dismiss on that dialog version: dialog.dismiss() or dialog.cancel() whenever you need to dismiss it.

방법 2:

I fixed it by adding a flag boolean in the viewmodel to detect loading state

public final MutableLiveData<Boolean> isLoading = new MutableLiveData<>();

and use it in getPosts() like this

public void getPosts() {
        Log.e(TAG, finalURL.getValue());

        isLoading.setValue(true);
        repository.remoteDataSource.getPostList(finalURL.getValue())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Response<PostList>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull Response<PostList> postListResponse) {

                        if (postListResponse.isSuccessful()) {
                            if (postListResponse.body() != null
                                    && postListResponse.body().getNextPageToken() != null) {
                                Log.e(TAG, postListResponse.body().getNextPageToken());
                                token.setValue(postListResponse.body().getNextPageToken());
                                isLoading.setValue(false);
                            }
                            postListMutableLiveData.setValue(postListResponse.body());

and finally in the fragment on button click

binding.loadMoreBtn.setOnClickListener(view ‑> {
            AlertDialog dialog = Utils.setProgressDialog(requireContext());

            postViewModel.isLoading.observe(getViewLifecycleOwner(), isLoading ‑> {
                if (isLoading) {
                    dialog.show();
                } else {
                    dialog.dismiss();
                }
            });

            if (Utils.hasNetworkAccess(requireContext())) {
                postViewModel.getPosts();
                Log.w(TAG, "loadMoreBtn: " + dialog.isShowing());
            } else {
                postViewModel.isLoading.postValue(true);
                postViewModel.getAllItemsFromDataBase.getValue();
                postViewModel.isLoading.postValue(false);
            }

        });

(by Dr MidoZainDr Mido)

참조 문서

  1. Alertdialog running ongoing dosen't dismiss or cancel (CC BY‑SA 2.5/3.0/4.0)

#android-progressbar #android-alertdialog #Android #android-dialog #java






관련 질문

목록 보기 항목의 보기는 화면에서 보기를 스크롤한 후 원래 상태로 돌아갑니다. (listview item's view returns to original state after scroll the view off the screen)

Android의 비동기 클래스에서 FTP 다운로드에 진행률 표시줄을 표시하는 방법은 무엇입니까? (How to show the progress bar in FTP download in async class in Android?)

Android에서 진행률 표시줄의 ListView (ListView of Progress Bars in android)

안드로이드에서 24시간 SeekBar 또는 ProgressBar를 만드는 방법 (How to create 24hour SeekBar or ProgressBar in android)

Android: ProgressBar가 활동에서 이상하게 보입니다. (Android: ProgressBar looks strange in activity)

Android에서 기본 ProgressDialog 원 색상을 변경하는 방법 (How to change default ProgressDialog circle color in android)

Android: 사이에 공백이 있는 맞춤 원 ProgressBar (Android: Custom circle ProgressBar with spaces in between)

정적 수평 진행률 표시줄 Android (Static horizontal progress bar android)

Android progressBar setVisibility()가 작동하지 않음 (Android progressBar setVisibility() not working)

비동기 작업의 게시 진행률 (Publishing progress in async task)

BaseActvity/BaseFragment의 ProgressBar 관리 (ProgressBar management in BaseActvity/BaseFragment)

진행 중인 경고 대화 상자가 닫히거나 취소되지 않음 (Alertdialog running ongoing dosen't dismiss or cancel)







코멘트