如何在Android中初始化类并将对象传递给构造函数?

时间:2018-11-20 11:45:54

标签: java android

我有以下课程:

public class MovieViewModel extends ViewModel {
    private String query;

    public MovieViewModel() {
        MyFactory factory = new MyFactory(); //Pass the query in the constructor
        //other stuff
    }
}

在我的MainActivity中,我正在创建此类的对象,如下所示:

MovieViewModel model = ViewModelProviders.of(this).get(MovieViewModel.class);

如何创建MovieViewModel类的对象,并同时初始化query字符串,以便可以将其传递给MyFactory构造函数?

2 个答案:

答案 0 :(得分:1)

您必须提供工厂类:

public class MovieViewModel extends ViewModel {
    private String query;

    MovieViewModel(String objectToBePassed) {
        //other stuff
    }

    static class MovieViewModelFactory extends ViewModelProvider.NewInstanceFactory {
        private String mObject;

        public MovieViewModelFactory(String objectToBePassed) {
            mObject = objectToBePassed;
        }

        @NonNull
        @Override
        public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
            return (T) new MovieViewModel(mObject);
        }
    }
}

和用法

ViewModelProviders.of(context,
            new MovieViewModel.MovieViewModelFactory(object))
            .get(MovieViewModel.class);

答案 1 :(得分:1)

您可以创建自定义工厂。

L

现在您可以像这样使用

public class MovieViewModelFactory implements ViewModelProvider.Factory {
    private Application mApplication;
    private String mParam;


    public MovieViewModelFactory(Application application, String param) {
        mApplication = application;
        mParam = param;
    }


    @Override
    public <T extends ViewModel> T create(Class<T> modelClass) {
        return (T) new MovieViewModel(mApplication, mParam);
    }
}