我想将我的参数从 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/