Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

android - How to use a ViewModelProvider.Factory when extends from AndroidViewModel

I want to send an extra parameter to my ViewModel, but this extends from AndroidViewModel. How can I add this parameter to the ViewModelFactory class ?

ViewModel

class ProjectViewModel(application: Application) : AndroidViewModel(application) {

    // need a param for project id...
}

ViewModelFactory

class ProjectViewModelFactory(val projectId: Int): ViewModelProvider.Factory {

    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        // need to send this...
        return ProjectViewModel(projectId) as T
    }
}

Note: I notice that in the documentation its says: AndroidViewModel Subclasses must have a constructor which accepts Application as the only parameter.

So I don't know if it is posible (or good) to do what I'm trying to do.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Get ViewModel:

        viewModel = ViewModelProviders.of(this,
                new BListFactory(getActivity().getApplication(), 1))
                .get(BListViewModel.class);

Factory:

class BListFactory extends ViewModelProvider.NewInstanceFactory {

    @NonNull
    private final Application application;

    private final long id;

    public BListFactory(@NonNull Application application, long id) {
        this.application = application;
        this.id = id;
    }

    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        if (modelClass == BListViewModel.class) {
            return (T) new BListViewModel(application, id);
        }
        return null;
    }
}

AndroidViewModel:

public class BListViewModel extends AndroidViewModel {

    private final long id;

    public BListViewModel(@NonNull Application application, final long id) {
        super(application);
        this.id = id;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...