如何在Android中实现ViewModel Factory

问题描述 投票:0回答:1

我正在用Room实现ViewModel数据库。一切正常。但是要求是我想使用ViewModel提供对AndroidViewModelFactory的依赖。我可以创建实现ViewModelFactoryViewModelProvider.Factory类。我传递一个普通的String作为对ViewModel的依赖。工厂类的代码是

public class TestViewModelFactory  implements ViewModelProvider.Factory{
    private static final String DEFAULT_LIMIT = "4";
    static Application application;
    static String created="ViewModelFactorySuccess";

    public static TestViewModelFactory createFactory(Activity activity) {
        application = activity.getApplication();
        if (application == null) {
            throw new IllegalStateException("Not yet attached to Application");
        }
        return new TestViewModelFactory(application, created);
    }
    public TestViewModelFactory(Application application, String created) {
        application=application;
        created=created;

    }
    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        try {
            return modelClass.getConstructor(TestViewModel.class, int.class)
                    .newInstance(application, created);
        } catch (NoSuchMethodException | IllegalAccessException |
                InstantiationException | InvocationTargetException e) {
            throw new RuntimeException("Cannot create an instance of " + modelClass, e);
        }
    }
}  

MainActivity中,ViewModel的普通实例创建为

TestViewModel testViewModel=new ViewModelProvider.AndroidViewModelFactory(getApplication()).create(TestViewModel.class);  

工作正常。但是如何创建ViewModel工厂类的实例,以便可以为ViewModel提供依赖项。请为ViewModel实例创建建议正确的方法。任何帮助,将不胜感激。

android mvvm factory-pattern android-mvvm
1个回答
0
投票

一般示例,

MyViewModel myViewModel = ViewModelProviders.of(this, new MyViewModelFactory(this.getApplication(), "Your string parameter")).get(MyViewModel.class);

就您而言,

TestViewModel testViewModel = ViewModelProviders.of(this, new TestViewModelFactory(this.getApplication(),"Your String Parameter").get(TestViewModel.class)
© www.soinside.com 2019 - 2024. All rights reserved.