我有一个 Fragment,从那个 Fragment 显示一个 DialogFragment,我希望 DialogFragment 向 Fragment 发送消息,或者 rech Fragment 的变量。我该怎么做?
问问题
1840 次
2 回答
3
You probably want to utilize a Listener pattern for this. Here's a quick example to get you started:
public class MyDialogFragment extends DialogFragment {
public interface MyDialogFragmentListener {
public void abstract onDialogMessage(int someValueIWantToSendToFragment);
}
private MyDialogFragmentListener mListener;
....
public void setListener(MyDialogFragmentListener listener) {
mListener = listener;
}
}
and then whenever you need to send some bit of data to your fragment from the dialog, call mListener.onDialogMessage(someValue);
Make sure that when you create your dialogfragment, you call setListener on it with an instance of MyDialogFragmentListener.
于 2012-04-14T20:17:16.987 回答
0
您可以将此代码放在 dialogFragment 中所需的位置:
Bundle args = new Bundle();
args.putString("message",myMessage);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
Fragment fragment = Fragment.instantiate(getActivity(), MyFragment.class.getName(), args);
ft.replace(R.id.details, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
例如,在onCreate
对话框片段中,我们使用 bundle 发送消息:
public static class MyDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String myMessage="Hello Fragment";
Bundle args = new Bundle();
args.putString("message",myMessage);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
Fragment fragment = Fragment.instantiate(getActivity(), MyFragment.class.getName(), args);
ft.replace(R.id.details, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.ic_dialog_about)
.setTitle(R.string.about)
.setMessage(R.string.about_message)
// ...
.create();
}
}
在MyFragment
我可以得到我的信息,只使用这一行:
getArguments().getString("message");
于 2012-04-15T10:45:31.163 回答