How to pass data between fragments

后端 未结 13 2770
醉话见心
醉话见心 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:07

    1- The first way is define an interface

    public interface OnMessage{
        void sendMessage(int fragmentId, String message);
    }
    
    public interface OnReceive{
        void onReceive(String message);
    }
    

    2- In you activity implement OnMessage interface

    public class MyActivity implements OnMessage {
       ...
       @Override
       public void sendMessage(int fragmentId, String message){
           Fragment fragment = getSupportFragmentManager().findFragmentById(fragmentId);
           ((OnReceive) fragment).sendMessage();
       }
    }
    

    3- In your fragment implement OnReceive interface

    public class MyFragment implements OnReceive{
        ...
        @Override
        public void onReceive(String message){
            myTextView.setText("Received message:" + message);
        }
    }
    

    This is the boilerplate version of handling message passing between fragments.

    Another way of handing data passage between fragments are by using an event bus.

    1- Register/unregister to an event bus

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

    2- Define an event class

    public class Message{
        public final String message;
    
        public Message(String message){
            this.message = message;
        }
    }
    

    3- Post this event in anywhere in your application

    EventBus.getDefault().post(new Message("hello world"));
    

    4- Subscribe to that event to receive it in your Fragment

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(Message event){
        mytextview.setText(event.message);
    }
    

    For more details, use cases, and an example project about the event bus pattern.

    0 讨论(0)
  • 2020-11-22 07:07

    Basically here we are dealing with communication between Fragments. Communication between fragments can never be directly possible. It involves activity under the context of which both the fragments are created.

    You need to create an interface in the sending fragment and implement the interface in the activity which will reprieve the message and transfer to the receiving fragment.

    0 讨论(0)
  • 2020-11-22 07:09

    you can read this doc .this concept is well explained here http://developer.android.com/training/basics/fragments/communicating.html

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 07:20

    Basically Implement the interface to communicate between Activity and fragment.

    1) Main activty

    public class MainActivity extends Activity implements SendFragment.StartCommunication
    {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    }
    
    @Override
    public void setComm(String msg) {
    // TODO Auto-generated method stub
    DisplayFragment mDisplayFragment = (DisplayFragment)getFragmentManager().findFragmentById(R.id.fragment2);
    if(mDisplayFragment != null && mDisplayFragment.isInLayout())
    {
    mDisplayFragment.setText(msg);
    }
    else
    {
    Toast.makeText(this, "Error Sending Message", Toast.LENGTH_SHORT).show();
    }
    }
    }
    

    2) sender fragment (fragment-to-Activity)

    public class SendFragment extends Fragment
    {
    StartCommunication mStartCommunicationListner;
    String msg = "hi";
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View mView = (View) inflater.inflate(R.layout.send_fragment, container);
    final EditText mEditText = (EditText)mView.findViewById(R.id.editText1);
    Button mButton = (Button) mView.findViewById(R.id.button1);
    mButton.setOnClickListener(new OnClickListener() {
    
    @Override
    public void onClick(View arg0) {
    // TODO Auto-generated method stub
    msg = mEditText.getText().toString();
    sendMessage();
    }
    });
    return mView;
    }
    
    interface StartCommunication
    {
    public void setComm(String msg);
    }
    
    @Override
    public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
    if(activity instanceof StartCommunication)
    {
    mStartCommunicationListner = (StartCommunication)activity;
    }
    else
    throw new ClassCastException();
    
    }
    
    public void sendMessage()
    {
    mStartCommunicationListner.setComm(msg);
    }
    
    }
    

    3) receiver fragment (Activity-to-fragment)

        public class DisplayFragment extends Fragment
    {
    View mView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    mView = (View) inflater.inflate(R.layout.display_frgmt_layout, container);
    return mView;
    }
    
    void setText(String msg)
    {
    TextView mTextView = (TextView) mView.findViewById(R.id.textView1);
    mTextView.setText(msg);
    }
    
    }
    

    I used this link for the same solution, I hope somebody will find it usefull. Very simple and basic example.

    http://infobloggall.com/2014/06/22/communication-between-activity-and-fragments/

    0 讨论(0)
  • 2020-11-22 07:21

    From the Fragment documentation:

    Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

    So I suggest you have look on the basic fragment training docs in the documentation. They're pretty comprehensive with an example and a walk-through guide.

    0 讨论(0)
提交回复
热议问题