Android: Passing Objects Between Fragments

前端 未结 4 1892
旧巷少年郎
旧巷少年郎 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:35

    I used to set object with Pacelable or Serializable to transfer, but whenever I add other variables to object(model), I have to register it all. It's so inconvenient.

    It's super easy to transfer object between activities or fragments.

    Android DataCache

    1. put your data object to KimchiDataCache instance in your activity or fragment.

      User userItem = new User(1, "KimKevin");  // Sample Model
      
      KimchiDataCache.getInstance().put(userItem);
      
      // add your activity or fragment
      
    2. Get your data object in your activity of fragment that you added.

      public class MainFragment extends Fragment{
           private User userItem;
      
           @Override
           public void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
      
               userItem = KimchiDataCache.getInstance().get(User.class);
           }
      

提交回复
热议问题