0

我正在使用 onCreateDialog 方法,但不推荐使用。

现在,我正在使用一个类来制作带有 DialogFragment 的对话框,但是在关闭对话框时我遇到了问题。

CustomDialogFragment 类:

package com.teste.dialogfragment;

import android.app.Dialog;
import android.app.DialogFragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;


public class CustomDialogFragment extends DialogFragment {


private ProgressDialog pDialog;


public static DialogFragment newInstance(int id) {
    CustomDialogFragment frag = new CustomDialogFragment();
    Bundle args = new Bundle();
    args.putInt("dialog_id", id);
    frag.setArguments(args);
    return frag;
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Log.i("teste RETORNO:", String.valueOf(getDialogId()));

    switch (getDialogId()) {
        case 0: // setamos como 0 (horizontal)
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Wait...downlading file.");
            pDialog.setIndeterminate(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pDialog.setCancelable(true);
            pDialog.show();
            return pDialog;
        default:
            return null;
    }


}

@Override
public void onCancel(DialogInterface dialog) {
    // use switch statement as the number of cancellable dialogs increase
    //if (getDialogId() == Constants.SHOW_LOGIN_DIALOG) {
        // cancel login here
    //}
    pDialog.dismiss();;
}




public int getDialogId() {
    return getArguments().getInt("dialog_id");
}

}

和主班。

公共类 Activity_dashboard 扩展 Activity{

Button btnShowProgress;

public static final int progress_bar_type = 0;

private DialogFragment mDialogFragment = null;

// files to download
private static String file_url_file_01   = "http://www.teste.com.br/teste_01.json";
private static String file_url_file_02 = "http://www.teste.com.br/teste_02.json";
private static String file_url_file_03 = "http://www.teste.com.br/teste_03.json";
private static String file_url_file_04   = "http://www.teste.com.br/teste_04.json";

public static int MY_COUNT = 4;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dashboard);

    btnShowProgress = (Button) findViewById(R.id.btGetFiles);
    btnShowProgress.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MY_COUNT = 4;

            // starting new Async Task
            new DownloadFileFromURL().execute(file_url_auditar, "teste_01.json");
            new DownloadFileFromURL().execute(file_url_hospitais, "teste_02.json");
            new DownloadFileFromURL().execute(file_url_pacientes, "teste_03.json");
            new DownloadFileFromURL().execute(file_url_login, "teste_04.json");
        }
    });
}


/**
 * Background Async Task
 * */
class DownloadFileFromURL extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        if(MY_COUNT == 4){
            super.onPreExecute();
            FragmentManager manager = getFragmentManager();
            mDialogFragment  = CustomDialogFragment.newInstance(progress_bar_type);
            mDialogFragment.show(manager, "dialog");
        }
    }

    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {

            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();
            // this will be useful so that you can show a tipical 0-100% progress bar
            int lenghtOfFile = conection.getContentLength();

            //file name
            File pathToWrite = new File(Environment.getExternalStorageDirectory() + "/teste/");
            File myFile = new File(pathToWrite, f_url[1]);

            if(!pathToWrite.exists()){
                pathToWrite.mkdirs();
            }

            // download the file
            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            // Output stream                    
            OutputStream output = new FileOutputStream(myFile, false);

            byte data[] = new byte[1024];
            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
                publishProgress(""+(int)((total*100)/lenghtOfFile));

                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();

            MY_COUNT--;

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return null;
    }



    //protected void onProgressUpdate(Integer... values) {
        //mDialogFragment.setProgress(values[0]);
    //}


    @Override
    protected void onPostExecute(String file_url) {
       if(MY_COUNT == 0){

            Toast.makeText(getBaseContext(), "Files Updated!", Toast.LENGTH_LONG).show();
            getFragmentManager().beginTransaction().remove(mDialogFragment).commitAllowingStateLoss();
            mDialogFragment.dismiss();
    }
}

}

看看我叫什么 AsyncTask 4 次,因为我必须下载 4 个文件。原来是打开了Dialog,但是当我调用OnPostExecute时,他关闭了Dialog:

protected void onPostExecute(String file_url) {
if(MY_COUNT == 0){
            Toast.makeText(getBaseContext(), "Files Updated!", Toast.LENGTH_LONG).show();
            getFragmentManager().beginTransaction().remove(mDialogFragment).commitAllowingStateLoss();
            mDialogFragment.dismiss();
        }
}

}

它也有问题,当我们通过下载进行更新时,我无法传递进度条的进度

protected void onProgressUpdate(Integer... values) {
        mDialogFragment.setProgress(values[0]);
    }
4

1 回答 1

1

你必须用 0 初始化 MY_COUNT 并在 onPreExecute 中增加它。像这样:

public static int MY_COUNT = 0;

@Override
protected void onPreExecute() {
    if(MY_COUNT++ == 0){
        super.onPreExecute();
        FragmentManager manager = getFragmentManager();
        mDialogFragment  = CustomDialogFragment.newInstance(progress_bar_type);
        mDialogFragment.show(manager, "dialog");
    }
}

在您的代码中, if(MY_COUNT == 4) 始终为真,因为您仅在下载完成后才减少它,这就是它被调用 4 次的原因。

于 2013-05-30T22:50:37.783 回答