如何在DialogFragment上执行AsyncTask?

时间:2014-05-26 08:54:44

标签: android listview android-asynctask dialogfragment

我想做的是,我想至少,当DialogFragment被解散时刷新ListView。整个刷新过程在我的AsyncTask中。我发现了很多问题/答案,但在我的案例中没有任何帮助。

我试过了:

1)我的DialogFragment中的onDismiss,获取AsyncTask本地类的实例并执行它。但是我有很多错误,我想是因为我试图创建一个新的Activity,每次对话都被解雇,实际上没有任何意义,而且还会更多地占用内存。

@Override
    public void onDismiss(DialogInterface dialog) {
        MainActivity outterObject = new MainActivity();
        MainActivity.LoadApplications buffer = outterObject.new LoadApplications();
        buffer.execute();
    }

2)在MainActivity中onResume,因为我认为Activity在Dialog出现时进入状态'暂停'。但它只在我再次关闭并打开我的应用程序时刷新ListView。

@Override
    protected void onResume() {
        super.onResume();
        new LoadApplications().execute();
    }

2 个答案:

答案 0 :(得分:1)

Activity方法中实例化onDismiss方式是错误的。永远不应该这样做。

您似乎需要一种在DialogFragmentActivity之间进行通信的方式。这个确切的主题在docs中清楚地呈现。在您的情况下,这可能是一个潜在的实现:

interface Refresher {
  void onRefresh();
}

class MainActivity extends Activity implements Refresher {

  // ... 

  void onRefresh() {
    new LoadApplications().execute();
  }  

}

class MyDialogFragment extends DialogFragment {

  private Refresher mRefresher;

  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
      mRefresher = (Refresher) activity;
    } catch (ClassCastException ex) {
      throw new ClassCastException("Activity must implement Refresher interface!");
    }
  }

  @Override
  public void onDismiss(DialogInterface dialog) {
    super.onDismiss(dialog);
    mRefresher.onRefresh();
  }

} 

答案 1 :(得分:0)

在对话框中尝试此操作

public class CustomDialogFragment extends DialogFragment
{

    private OnDismissListener onDismissListener;


    @Override
    public Dialog onCreateDialog(final Bundle savedInstanceState)
    {
        Dialog dialog = super.onCreateDialog(savedInstanceState);        
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener()
        {
            @Override
            public void onDismiss(final DialogInterface dialog)
            {
                if (onDismissListener != null)
                    onDismissListener.onDismiss();
            }
        });
        return dialog;
    }

    public interface OnDismissListener
    {
        public void onDismiss();
    }

    public void setOnDismissListener(final OnDismissListener onDismissListener)
    {
        this.onDismissListener = onDismissListener;
    }
}

并致电您的活动

myCustomDialogFragment.setOnDismissListener(new FAQDialog.OnDismissListener() {
                    @Override
                    public void onDismiss()
                    {

                    }
                });