如何从DialogFragment数据发送到一个片段? [英] How to send data from DialogFragment to a Fragment?

查看:119
本文介绍了如何从DialogFragment数据发送到一个片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个片段,打开一个dial​​ogfragment获取用户输入(字符串和整数)。如何发送这两样东西回片段?

I have a fragment that opens a dialogfragment to get user input (a string, and an integer). How do I send these two things back to the fragment?

下面是我的DialogFragment:

Here is my DialogFragment:

public class DatePickerFragment extends DialogFragment {
    String Month;
    int Year;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().setTitle(getString(R.string.Date_Picker));
        View v = inflater.inflate(R.layout.date_picker_dialog, container, false);

        Spinner months = (Spinner) v.findViewById(R.id.months_spinner);
        ArrayAdapter<CharSequence> monthadapter = ArrayAdapter.createFromResource(getActivity(),
                R.array.Months, R.layout.picker_row);
              months.setAdapter(monthadapter);
              months.setOnItemSelectedListener(new OnItemSelectedListener(){
                  @Override
                  public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int monthplace, long id) {
                      Month = Integer.toString(monthplace);
                  }
                  public void onNothingSelected(AdapterView<?> parent) {
                    }
              });

        Spinner years = (Spinner) v.findViewById(R.id.years_spinner);
        ArrayAdapter<CharSequence> yearadapter = ArrayAdapter.createFromResource(getActivity(),
             R.array.Years, R.layout.picker_row);
        years.setAdapter(yearadapter);
        years.setOnItemSelectedListener(new OnItemSelectedListener(){
          @Override
          public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int yearplace, long id) {
              if (yearplace == 0){
                  Year = 2012;
              }if (yearplace == 1){
                  Year = 2013;
              }if (yearplace == 2){
                  Year = 2014;
              }
          }
          public void onNothingSelected(AdapterView<?> parent) {}
        });

        Button button = (Button) v.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
           public void onClick(View v) {
               getDialog().dismiss();
            }
        });

        return v;
    }
}

我需要的数据后,按一下按钮和getDialog()之前发送。解雇()

I need to send the data after the button click and before getDialog().dismiss()

下面是需要被发送到该数据中的片段:

Here is the fragment that data needs to be sent to:

public class CalendarFragment extends Fragment {
int Year;
String Month;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    int position = getArguments().getInt("position");
    String[] categories = getResources().getStringArray(R.array.categories);
    getActivity().getActionBar().setTitle(categories[position]);
    View v = inflater.inflate(R.layout.calendar_fragment_layout, container, false);    

    final Calendar c = Calendar.getInstance();
    SimpleDateFormat month_date = new SimpleDateFormat("MMMMMMMMM");
    Month = month_date.format(c.getTime());
    Year = c.get(Calendar.YEAR);

    Button button = (Button) v.findViewById(R.id.button);
    button.setText(Month + " "+ Year);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
           new DatePickerFragment().show(getFragmentManager(), "MyProgressDialog");
        }
    });
   return v;
  }
}

,以便当用户选择在dialogfragment一个日期,它必须返回月份和年份。

so once the user selects a date in the dialogfragment, it must return the month and year.

然后,在按钮上的文本应更改为用户指定的月份和年份。

Then, the text on the button should change to the month and year specified by user.

推荐答案

下面的食谱:

  1. 创建接口(即 MyDialogCallbackInterface )与所使用的方法来传递数据,你需要回到调用片段(即 methodToPassDataBackToFragment(...的数据); )。
  2. 确保你的片段实现这个接口:类MyFragment扩展片段实现MyDialogCallbackInterface {...}
  3. 在创建 DialogFragment 的设置调用片段作为DialogFragment的目标通过调用 myFragmentDialog。 setTargetFragment(此,0)
  4. DialogFragment ,获取片段对象 getTargetFragment(); 丢你创建的界面确保你要调用由该片段实现的方法: MyDialogCallbackInterface mHost =(MyDialogCallbackInterface)getTargetFragment(); 。注意:您将获得 ClassCastException异常如果您的目标片段是不是实现了这个接口,但是我个人让我的code坠毁这里由未捕获该异常,因为这是应该永远不会发生。
  5. 当时间一到,叫 methodToPassData()方法传递你想要的数据,也就是类似这样的((MyDialogCallbackInterface)getTargetFragment())。methodToPassDataBackToFragment (数据); 。如果你丢在目的片段已经在 onAttach(),那么这个code看起来像 mHost.methodToPassDataBackToFragment(数据);
  6. 瞧。您刚刚成功从对话框返回到调用片段传递您的数据。
  1. Create Interface (i.e. MyDialogCallbackInterface) with the method to be used to pass the data you need back to invoking Fragment (i.e. methodToPassDataBackToFragment(... data);).
  2. Ensure your Fragment implements this interface: class MyFragment extends Fragment implements MyDialogCallbackInterface {....}
  3. Upon creation of DialogFragment set your invoking Fragment as DialogFragment's target by calling myFragmentDialog.setTargetFragment(this, 0);.
  4. In your DialogFragment, get that fragment object with getTargetFragment(); and cast into the interface you created to ensure method you want to call is implemented by that fragment: MyDialogCallbackInterface mHost = (MyDialogCallbackInterface)getTargetFragment();. Note you will get ClassCastException if your target fragment is not implementing this interface, but I personally let my code crash here by not catching this exception, because this is what should never happen.
  5. When time comes, call methodToPassData() method to pass data you want, i.e. like this ((MyDialogCallbackInterface)getTargetFragment()).methodToPassDataBackToFragment(data);. If you did cast target fragment already in onAttach(), then this code would look like mHost.methodToPassDataBackToFragment(data);.
  6. Voilà. You just successfully passed your data from dialog back to invoking fragment.

这篇关于如何从DialogFragment数据发送到一个片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆