gpt4 book ai didi

android - 如果您从 Activity 与 Fragment 调用,是否从 DialogFragment 接收数据?

转载 作者:行者123 更新时间:2023-11-29 15:43:43 28 4
gpt4 key购买 nike

我这样称呼我的 DialogFragment:

如果我在 Activity 中:

MyDialogFragment dialogfragment = new MyDialogFragment();
dialogfragment.show(getFragmentManager(), "");

如果我已经在 fragment 中:

MyDialogFragment dialogfragment = new MyDialogFragment();
dialogfragment.show(getActivity().getFragmentManager(), "");

在 MyDialogFragment 中,它扩展了 XML 并允许用户向 EditTexts 等输入一些值,我希望能够将这些值返回到调用对话框的任何地方。

为了这个问题,假设我的对话框类想要返回一些私有(private)变量 String mNameint mValue

在不知道从何处调用对话框(Activity 或 Fragment)的情况下,是否有正确的方法来执行此操作?我如何传回这些值/如何接收它们?

最佳答案

如果你想从fragmentactivity发送数据。您可以通过以下方式调用 activitypublic 方法来做到这一点:

((MainActivity)getActivity()).sendData(Object object);

您不能将数据发送到 fragment

正如文档所说:

All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

你应该做的是:

  1. 在 fragment 中定义一个接口(interface)
  2. activity 中实现 Interface
  3. 将数据传送到activity
  4. 然后 activity 会将数据传递给其他一些 fragment

顺便说一句,您还可以使用这种做法将数据发送到 activity(到第 3 点为止)。

Reference and example

定义接口(interface):

public interface DataListener {
public void onDataReceived(Object obj);
}

fragment 中:

public class MyFragment extends Fragment {
DataListener callback;

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);

// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
callback = (DataListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement DataListener");
}
}
}

fragment 发送数据;

callback.onDataReceived(object); // some object data

activity中接收数据:

public static class MainActivity extends AppCompatActivity
implements DataListener{

public void onDataReceived(Object object) {
// Do something here with object data
}
}

现在,如果需要,您可以将此数据发送到任何其他 fragment

将数据从 activity 发送到其他一些 fragment:

AnotherFragment anotherFrag = (AnotherFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_container);

if (anotherFrag != null) {
anotherFrag.receiveDataInFrag(object);
}else{
// create a new instance of the fragment and pass data to it.
}

关于android - 如果您从 Activity 与 Fragment 调用,是否从 DialogFragment 接收数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36363185/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com