简体   繁体   中英

Pass data from Activity to Fragment that is already displayed

How do you pass a data from activity to fragment that's already active? I can transfer using a bundle but the only way I can get it is using createView on that fragment but my problem is it is already created. Is there anyway that I can pass data from activity to fragment and then call that data without using onCreateView

I tried this link to get what I needed but the data is not accessible due to static

If view is already created then onCreateview will not call so you can pass data via BroadcastReceiver

 BroadcastReceiver receiverUpdateDownload = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //Getdata from intent
        }
    };

Regester your BroadcastReceiver in onCreateView

IntentFilter filter = new IntentFilter("STRING_ID_FOR_BRODCAST");
getActivity().registerReceiver(receiverUpdateDownload, filter);

unregister your Receiver at onStop

@Override
public void onStop() {
    super.onStop();
    if (receiverUpdateDownload != null) {
        try {
            getActivity().unregisterReceiver(receiverUpdateDownload);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Call your brodcast from acttvity

 Intent intent = new Intent("STRING_ID_FOR_BRODCAST");
 intent.putExtra("key","value");
 sendBroadcast(intent);

There can be multiple ways

  • Get Fragment instance by using findFragmentById as @Belbahar Raouf showed.
  • Use BroadcastReceiver to send data between Activity , Fragment or Service . It works everywhere. But it can be little lengthy.
  • You can use EventBus , a great invention from GreenBot. Just one line to pass data.

    EventBus.getDefault().post(new MessageEvent());

See Event bus documentation for implementation.

Make a model class that will be passed MessageEvent.java .

public static class MessageEvent { /* Additional fields if needed */ }

Subscribe your listener in Fragment .

@Subscribe(threadMode = ThreadMode.MAIN)  
public void onMessageEvent(MessageEvent event) {/* Do something */};

Register & Unregister event bus with Fragment Lifecycle .

@Override
 public void onStart() {
     super.onStart();
     EventBus.getDefault().register(this);
 }

 @Override
 public void onStop() {
     super.onStop();
     EventBus.getDefault().unregister(this);
 }

From your Activity , just fire event, this will be received by Fragment .

EventBus.getDefault().post(new MessageEvent());

Before that add dependency to your gradle.

implementation 'org.greenrobot:eventbus:3.1.1'

Best thing of EventBus-

It works in Activity , Fragment & Services . You need not to make multiple broadcast receiver with multiple intent types. Just post event in one line code.

I also use EventBus for ease of use.

According to documentation :

The host activity can deliver messages to a fragment by capturing the Fragment instance with findFragmentById(), then directly call the fragment's public methods.

Example (declare this in your activity):

ArticleFragment articleFrag = (ArticleFragment)
           getSupportFragmentManager().findFragmentById(R.id.article_fragment);

        if (articleFrag != null) {
            // If article frag is available
            // Call a method in the ArticleFragment to update its content
            articleFrag.updateArticleView(position);
        }

And in your fragment implement the method that will do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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