Android: Passing Objects Between Fragments

前端 未结 4 1922
旧巷少年郎
旧巷少年郎 2021-01-05 04:00

Before i start, i have look through question such as:

Passing data between fragments: screen overlap How to pass values between Fragments

as well as Android

4条回答
  •  无人及你
    2021-01-05 04:22

    It's easy to share objects via implementing Serializable to your custom Object. I wrote a tutorial about this here.

    From Fragment One:

    android.support.v4.app.FragmentTransaction ft = 
        getActivity().getSupportFragmentManager().beginTransaction();
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    OfficeCategoryFragment frag = new OfficeCategoryFragment();
    
    Bundle bundles = new Bundle();
    Division aDivision = divisionList.get(position);
    
    // ensure your object has not null
    if (aDivision != null) {
        bundles.putSerializable("aDivision", aDivision);
        Log.e("aDivision", "is valid");
    } else {
        Log.e("aDivision", "is null");
    }
    frag.setArguments(bundles);
    ft.replace(android.R.id.content, frag);
    ft.addToBackStack(null);
    ft.commit();
    

    In Fragment two:

    Bundle bundle = getArguments();
    Division division= (Division) bundle.getSerializable("aDivision");
    Log.e("division TEST", "" + division.getName());
    

提交回复
热议问题