Pass data between two fragments without using activity

前端 未结 3 654
执念已碎
执念已碎 2020-12-03 13:17

I want to pass data between two fragments without using activity and fragment activity.

I don\'t want to pass data between fragments using activity like this : Commu

相关标签:
3条回答
  • 2020-12-03 13:24

    You can use EventBus https://github.com/greenrobot/EventBus to pass any complex object around in Android.

    Example passing an object from one Activity to another:

    Add your object on the EventBus:

    EventBus.getDefault().postSticky(anyObject);
    startActivity(new Intent(getActivity(), SomeActivity.class));
    

    Anywhere in SomeActivity:

    AnyObject anyObject = EventBus.getDefault().getStickyEvent(AnyObject.class);
    

    This examle is just to show that it works across Activities, you can call getStickyEvent to get anyObject anywhere in your code.

    So, you can post an object in Fragment A, and use getStickyEvent in fragment B to retrieve it.

    This is especially convenient if you have a lot of arguments and/or complex objects you wish to move from one place to the other. Simply create a single 'holder' object containing getter/setters for the arguments and then pass it along. Much simpler than having to pass them separately and somehow serialize the complex objects.

    0 讨论(0)
  • 2020-12-03 13:28

    Best Way to exchange data between activity/fragments, fragment/fragment/, activity/activity, class/ class, make a common singleton class like:

    public class DataHolderClass {
    private static DataHolderClass dataObject = null;
    
    private DataHolderClass() {
        // left blank intentionally
    }
    
    public static DataHolderClass getInstance() {
        if (dataObject == null)
            dataObject = new DataHolderClass();
        return dataObject;
    }
    private String distributor_id;;
    
     public String getDistributor_id() {
        return distributor_id;
     }
    
     public void setDistributor_id(String distributor_id) {
        this.distributor_id = distributor_id;
     }
    }
    

    now set from anywhere(Fragment, activity, class) at any event before you move to new screen

    DataHolderClass.getInstance().setDistributor_id("your data");
    

    now get anywhere(Fragment, activity, class)

     String _data = DataHolderClass.getInstance().getDistributor_id();
    
    0 讨论(0)
  • 2020-12-03 13:36

    I think you are trying to pass data from one fragment to another fragment, So try using below code.

    Use a Bundle, So write below code in first fragment from where you want to send data.

    Fragment fragment = new Fragment();
    Bundle bundle = new Bundle();
    bundle.putString("message", "From Activity");
    fragment.setArguments(bundle);
    

    and to retrieve that data, use the following code in your other fragment

    String strtext=getArguments().getString("message");
    
    0 讨论(0)
提交回复
热议问题