可以从内部获取上下文 Fragment
做就是了
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);
Context context = getContext();
SomeViewModel someViewModel = ViewModelProviders.of(this).get(SomeViewModel.class);
Context context = homeViewModel.getContext();
return root;
}
}
您还可以AndroidViewModel
在onCreateView
方法中附加一个实现返回应用程序上下文的方法的方法
public class SomeViewModel extends AndroidViewModel {
private MutableLiveData<ArrayList<String>> someMutableData;
Context context;
public SomeViewModel(Application application) {
super(application);
context = getApplication().getApplicationContext();
someMutableData = new MutableLiveData<>();
.
.
}
public Context getContext() {
return context
}
}