用startactivitywithresult调用newinstance

时间:2014-11-24 19:27:24

标签: android android-dialogfragment

这就是我调用DialogFragment的方式

IncomeAdd dfIncomeAdd = IncomeAdd.newInstance(currentYear,currentMonth);
dfIncomeAdd.setTargetFragment(this, Activity.RESULT_OK);
dfIncomeAdd.show(getActivity().getSupportFragmentManager(),"fragmentDialog");

我需要DialogFragment将它的结果返回给我的调用片段,所以我使用onActivityResult但似乎onActivityResult没有被触发。我在某处读到了我需要通过使用StartActivityForResult调用它来启动DialogFragment活动。但是在使用newInstance时如何调用StartActivityForResult?

2 个答案:

答案 0 :(得分:0)

为什么需要调用onActivityResult。 您可以在Activity类中创建一个方法,例如:

dialogListener(String... args)      //data to be sent from dialog will go in as arguments, that's a var-arg syntax
{
   //write code which you intented to write in onActivityResult
}

在您关闭对话框时调用此方法。

答案 1 :(得分:0)

您可以使用以下模式。首先创建对话框侦听器:

public class IncomeAdd extends DialogFragment {
  public interface OnSomethingChanged {
      public void onChange(int value);
  }

  OnSomethingChanged mListener;

  public void setListener(OnSomethingChanged l) {
      mListener = l;
  }
}

现在,您应该在点击mListener.onChange(dialogValue)按钮时致电OK

builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        if(mListener != null) {
            mListener.onDateChange(dialogValue);
        }
    }
});

显示对话框:

IncomeAdd dfIncomeAdd = IncomeAdd.newInstance(currentYear,currentMonth);
dfIncomeAdd.setListener(new OnSomethingChanged() {

  public void onChange(int value) {
      // do with value what you want
  }

});
dfIncomeAdd.show(getActivity(),"fragmentDialog");