gpt4 book ai didi

android - 我可以为一个 fragment 使用两个 View 模型吗?

转载 作者:搜寻专家 更新时间:2023-11-01 08:17:40 27 4
gpt4 key购买 nike

我在我的 Android 项目中使用 MVVM。我有创建和编辑 fragment 。这 2 个 fragment 具有大致相同的功能。如果我在公共(public) View 模型中编写具有相同功能的函数,我可以将公共(public) View 模型与自己的 fragment View 模型一起使用吗?例如,我可以像下面这样使用吗?

 CommonViewModel(){

void selectPriority()
.
.
.
otherthings...}

 CreateViewModel(){

LiveData<CommonViewModel> cvm;
.
.
.
otherthings...}

  EditViewModel(){

LiveData<CommonViewModel> cvm;
.
.
.
otherthings...}

代替这个

 CreateViewModel(){

void selectPriority()
.
.
.
otherthings...}

  EditViewModel(){

void selectPriority()
.
.
.
otherthings...}

或者你能建议我使用不同的方式吗?

最佳答案

你可以通过继承来做到这一点,制作一个通用的 View 模型并在编辑和创建 View 模型中扩展它,比如

class CreatEditViewModel{

public void selectPriority(){
//to something....
}
public void other(){
//to something....
}

class CreateViewModel extends CreatEditViewModel{

class EditViewModel extends CreatEditViewModel{

您不能将这些逻辑放在 BaseViewModel 中,因为 BaseViewModel 由所有 ViewModel 扩展。

关于android - 我可以为一个 fragment 使用两个 View 模型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57492972/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com