Best practice for instantiating a new Android Fragment

前端 未结 13 1520
暖寄归人
暖寄归人 2020-11-21 04:38

I have seen two general practices to instantiate a new Fragment in an application:

Fragment newFragment = new MyFragment();

and

<         


        
13条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 05:01

    Since the questions about best practice, I would add, that very often good idea to use hybrid approach for creating fragment when working with some REST web services

    We can't pass complex objects, for example some User model, for case of displaying user fragment

    But what we can do, is to check in onCreate that user!=null and if not - then bring him from data layer, otherwise - use existing.

    This way we gain both ability to recreate by userId in case of fragment recreation by Android and snappiness for user actions, as well as ability to create fragments by holding to object itself or only it's id

    Something likes this:

    public class UserFragment extends Fragment {
        public final static String USER_ID="user_id";
        private User user;
        private long userId;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            userId = getArguments().getLong(USER_ID);
            if(user==null){
                //
                // Recreating here user from user id(i.e requesting from your data model,
                // which could be services, direct request to rest, or data layer sitting
                // on application model
                //
                 user = bringUser();
            }
        }
    
        public static UserFragment newInstance(User user, long user_id){
            UserFragment userFragment = new UserFragment();
            Bundle args = new Bundle();
            args.putLong(USER_ID,user_id);
            if(user!=null){
                userFragment.user=user;
            }
            userFragment.setArguments(args);
            return userFragment;
    
        }
    
        public static UserFragment newInstance(long user_id){
            return newInstance(null,user_id);
        }
    
        public static UserFragment newInstance(User user){
            return newInstance(user,user.id);
        }
    }
    

提交回复
热议问题