简体   繁体   English

如何将数据从活动传递到片段

[英]How to pass data from an Activity to a Fragment

In my project I have to pass some data in a fragment activity . 在我的项目中,我必须通过片段活动传递一些数据。 How do i do that ? 我怎么做 ? I have tried like this : 我已经这样尝试过:

String json_string = "s";
Intent intent = new Intent(context, ShowMapFragement.class);
intent.putExtra("json_data", json_string);
context.startActivity(intent);

But it's not working properly. 但是它不能正常工作。 Please help me. 请帮我。

Here is one way to pass data from an Activity to a Fragment: 这是将数据从活动传递到片段的一种方法:

Create a static newInstance() method in the Fragment class: 在Fragment类中创建一个静态newInstance()方法:

public static MyFragment newInstance(String valueToPass) {
    MyFragment instance = new MyFragment();
    Bundle args = new Bundle();
    args.putString("key", valueToPass);
    instance.setArguments(args)
    return instance;
}

Pass the data from the Activity/Fragment to MyFragment like so: 将数据从活动/片段传递到MyFragment,如下所示:

MyFragment myFragment = MyFragment.newInstance("Hello World");

Then you can do this to retrieve the data (any time after Fragment.onCreate()) 然后,您可以执行此操作以检索数据(在Fragment.onCreate()之后的任何时间)

   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

       if (getArguments() != null) {
           String passedValue = getArguments().getString("key");
           // passedValue == "Hello World"
       }   
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM