java - 如何将参数从 Activity 传递到 Fragment 中的函数

标签 java android android-activity fragment

我想将我的参数从 Activity 传递到 fragment ,我该怎么做?

Activity.java

fragment.getViewProfileMainActivity(SendViewProfileName, SendViewProfileEmail, SendViewProfilePhone, SendViewProfileCity, SendViewProfileGender, SendViewProfileBirthdate, SendViewProfilePhotoUrl);

Fragment.java

getViewProfileMainActivity(String Profile, ...);

最佳答案

为了在应用程序的各个组件之间传递消息,我强烈建议您使用发布者/订阅者的成熟解决方案 EventBus

  • 要将 EventBus 添加为项目中的依赖项,请在应用级 build.gralde 文件中添加以下行:
    implementation 'org.greenrobot:eventbus:3.1.1'

请注意,在撰写此答案时,最新版本是 3.1.1。您应该从 here 检查最新版本并包括这一点。

  • 将事件类定义为简单的 POJO:
    public class MessageEvent {
        public final String message;

        public MessageEvent(String message) {
            this.message = message;
        }
    }
  • 在您的 Fragment 中,添加此代码以监听事件
    // This method will be called when a MessageEvent is posted (in the UI thread for Toast)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        Toast.makeText(getActivity(), event.message, Toast.LENGTH_SHORT).show();
        // do something here
    }
  • 在您的 fragment 中,添加以下代码以在总线上注册和取消注册:
    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }
  • 最后,从您的 Activity 中发布事件:
    EventBus.getDefault().post(new MessageEvent("Hello everyone!"));

您的 Fragment 将收到此消息。

<小时/>

对于您的特定示例,您可以执行以下操作:

  • 您的事件 POJO 类应该是:
    public class MessageEvent {
        public final String SendViewProfileName;
        public final String SendViewProfileEmail;
        // similarly other params

        public MessageEvent(String SendViewProfileName, String SendViewProfileEmail, ...) {
            this.SendViewProfileName = SendViewProfileName;
            this.SendViewProfileEmail = SendViewProfileEmail;
            // similarly other params
        }
    }
  • 当事件发生时,您可以在 Fragment 中执行所需的方法,如下所示:
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        getViewProfileMainActivity(event.SendViewProfileName, ...);
    }

    private getViewProfileMainActivity(Profile, ...) {
         // your function definition here
    }
  • 在您的 Activity 中,您可以将 Activity 发布为:
    EventBus.getDefault().post(new MessageEvent(SendViewProfileName, SendViewProfileEmail, ...));

希望这有帮助!

关于java - 如何将参数从 Activity 传递到 Fragment 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58446719/

相关文章:

android - 如何在 Android.mk 中添加 C-only 选项?

android - 使用 URL 显示新 Activity ?

android - 如何创建在指定屏幕位置显示的 android Activity ?

c# - 将自定义对象传递给 Xamarin Android 中的下一个 Activity

java - 评估属性文件java中的属性值

java - ListView 项目在 setChoiceMode(ListView.CHOICE_MODE_NONE) 之后保持选中状态

java - 将 java.util.Date 设置为一天的开始

java - 返回数组的位置

java - 我如何从查询中的两个表中获取数据?

android - 如何使用 Parse.com 创建 ParseUsers 组?