Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 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 Answer

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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...