[英]how can I pass parameter from Activity to function in Fragment
I want to pass my parameter from activity to fragment how can I do it?我想将我的参数从活动传递到片段我该怎么做?
Activity.java活动.java
fragment.getViewProfileMainActivity(SendViewProfileName, SendViewProfileEmail, SendViewProfilePhone, SendViewProfileCity, SendViewProfileGender, SendViewProfileBirthdate, SendViewProfilePhotoUrl);
Fragment.java片段.java
getViewProfileMainActivity(String Profile, ...);
For passing messages between various components of your app, I would highly recommend you to use the seasoned solution of publisher/subscriber using EventBus为了在您的应用程序的各个组件之间传递消息,我强烈建议您使用使用EventBus的发布者/订阅者的经验丰富的解决方案
implementation 'org.greenrobot:eventbus:3.1.1'
Note that at the time of writing this answer, the latest version was 3.1.1.请注意,在撰写此答案时,最新版本是 3.1.1。 You should check the latest version from here and include that.
您应该从此处检查最新版本并将其包括在内。
public class MessageEvent {
public final String message;
public MessageEvent(String message) {
this.message = message;
}
}
// 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
}
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
EventBus.getDefault().post(new MessageEvent("Hello everyone!"));
Your Fragment will receive this message.您的 Fragment 将收到此消息。
Coming to your particular example, you can do so as follows:来到您的特定示例,您可以执行以下操作:
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
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
getViewProfileMainActivity(event.SendViewProfileName, ...);
}
private getViewProfileMainActivity(Profile, ...) {
// your function definition here
}
EventBus.getDefault().post(new MessageEvent(SendViewProfileName, SendViewProfileEmail, ...));
Hope this helps!希望这可以帮助!
Covered in the training at https://developer.android.com/training/basics/fragments/communicating.html#Deliver涵盖在https://developer.android.com/training/basics/fragments/communicating.html#Deliver的培训中
You just need get the fragment in your Activity您只需要在 Activity 中获取片段
ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id.article_fragment);
and then handle if it does not exist yet然后处理如果它还不存在
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.