Android SharedPreferences in Fragment

前端 未结 10 1671
萌比男神i
萌比男神i 2020-11-29 17:16

I am trying to read SharedPreferences inside Fragment. My code is what I use to get preferences in any other Activity.

     SharedPreferences preferences = g         


        
10条回答
  •  甜味超标
    2020-11-29 17:42

    It is possible to get a context from within a Fragment

    Just do

    public class YourFragment extends Fragment {
    
        public View onCreateView(@NonNull LayoutInflater inflater,
                                 ViewGroup container, Bundle savedInstanceState) {
            final View root = inflater.inflate(R.layout.yout_fragment_layout, container, false);
            // get context here
            Context context = getContext();
            // do as you please with the context
    
    
            // if you decide to go with second option
            SomeViewModel someViewModel = ViewModelProviders.of(this).get(SomeViewModel.class);
            Context context = homeViewModel.getContext();
            // do as you please with the context
            return root;
        }
    }
    

    You may also attached an AndroidViewModel in the onCreateView method that implements a method that returns the application context

    public class SomeViewModel extends AndroidViewModel {
    
        private MutableLiveData> someMutableData;
        Context context;
    
        public SomeViewModel(Application application) {
            super(application);
            context = getApplication().getApplicationContext();
            someMutableData = new MutableLiveData<>();
            .
            .
         }
    
         public Context getContext() {
             return context
         }
      }
    

提交回复
热议问题