简体   繁体   English

ViewModelProvider Fragment 实例化 model

[英]ViewModelProvider Fragment instantiate model

I have a model which is started on my "MainActivity.java" which is called like this:我有一个 model,它是在我的“MainActivity.java”上启动的,它的名称如下:

//MainActivity.java (public class MainActivity extends AppCompatActivity {...)
...
private ModelName mViewModel;
...
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mViewModel = new ViewModelProvider(this).get(ModelName.class);
}
...

As of now, I was using this approximation in each of my fragments to instantiate the same model and be able to interact with the variables within it:到目前为止,我在每个片段中都使用这个近似值来实例化相同的 model 并能够与其中的变量进行交互:

//FragmentClass.java (public class F1_Start_Acquisition extends Fragment {...)
...
private ModelName mViewModel;
...
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.f1__test__fragment, container, false);
        mViewModel = ViewModelProviders.of((FragmentActivity) 
              getActivity()).get(ModelName .class);
}

The ViewModelProviders.of got deprecated, and I see everywhere that it should be replaced with new ViewModelProvider(this).get(ModelName.class); ViewModelProviders.of已被弃用,我到处都看到它应该被替换为new ViewModelProvider(this).get(ModelName.class); , but I don't want to create a new instance of the model, I just want to get the existing instance already created, and I have tried many approaches which did not work... ,但我不想创建 model 的新实例,我只想获取已经创建的现有实例,并且我尝试了许多不起作用的方法......

Could someone please tell me how to access the already existing instance of the model from the Fragment.java initialisation class?有人可以告诉我如何从Fragment.java初始化 class 访问已经存在的 model 实例吗?

mViewModel = new ViewModelProvider(requireActivity()).get(ModelName.class);

When you use the above code.当你使用上面的代码时。 Notice that fragment retrieves the activity that contains them.请注意,片段检索包含它们的活动。 In this way, it will not instantiate a new object instead it will return the same as attached to the activity.这样,它不会实例化一个新的 object 而是返回与附加到活动相同的内容。

You can check by using the Logcat.您可以使用 Logcat 进行检查。 Just use mViewmodel.toString() in the activity and fragment.只需在活动和片段中使用mViewmodel.toString()

I hope you get it.我希望你能明白。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM