How to pass data between fragments

后端 未结 13 3012
醉话见心
醉话见心 2020-11-22 07:03

Im trying to pass data between two fragmens in my program. Its just a simple string that is stored in the List. The List is made public in fragments A, and when the user cli

13条回答
  •  醉梦人生
    2020-11-22 07:20

    IN my case i had to send the data backwards from FragmentB->FragmentA hence Intents was not an option as the fragment would already be initialised All though all of the above answers sounds good it takes a lot of boiler plate code to implement, so i went with a much simpler approach of using LocalBroadcastManager, it exactly does the above said but without alll the nasty boilerplate code. An example is shared below.

    In Sending Fragment(Fragment B)

    public class FragmentB {
    
        private void sendMessage() {
          Intent intent = new Intent("custom-event-name");
          intent.putExtra("message", "your message");
          LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        }
     }
    

    And in the Message to be Received Fragment(FRAGMENT A)

      public class FragmentA {
        @Override
        public void onCreate(Bundle savedInstanceState) {
    
          ...
    
          // Register receiver
          LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
              new IntentFilter("custom-event-name"));
        }
    
    //    This will be called whenever an Intent with an action named "custom-event-name" is broadcasted.
        private BroadcastReceiver receiver = new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
            String message = intent.getStringExtra("message");
          }
        };
    }
    

    Hope it helps someone

提交回复
热议问题