gpt4 book ai didi

android - 我们应该在哪里更新 MVVM 中的模型

转载 作者:行者123 更新时间:2023-12-03 10:42:05 24 4
gpt4 key购买 nike

我正在学习 MVVM。我正在阅读示例代码 https://codelabs.developers.google.com/codelabs/android-room-with-a-view关于 MVVM。有一个 Book 实体,它已从如下 Activity 更新:

Book book = new Book();
book.setName(x);

但我认为我们不应该在 View 层中有模型实例,我们应该在 ViewModel 中执行此操作,而不是在 View 中。类似于 View 中的以下代码:
MyViewModel viewModel = ViewModelProviders.of(this).get(MyViewModel.class);
viewModel.setBookName(x);

我的问题是我们可以在 View 中实例化一个实体吗?这样做的正确方法是什么?

最佳答案

您应该只更新 View 模型中的模型类..

为 Activity 创建接口(interface) IContract.java

 public interface IContract {

interface View
{
public void displayModelData();

}

interface ViewModel
{
public Book setModelData();
public Book getModelData();
}
}

  • Then implement View interface in Activity class and View Model Interface in ViewModel class..
  • Now create an reference ViewModel object in Activity class.

  • where we can pass the data from ViewModel to View using that object



Activity 课 MainActivity.java
public class MainActivity implements IContract.View {
private IContract.ViewModel viewModel; //create a instance for ViewModel object

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

this.viewModel = new MainActivityViewModel(getApplicationContext());// object initialisation


@overide
public void displayModelData()
{
viewModel.setModelData(); // update model class
Book obj = viewModel.getModelData();// this will get book object from viewModel class.
Toast(obj.Name);
}

}
}

MainActivityViewModel.java
  public class MainActivityViewModelimplements IContract.ViewModel

{
Context context;
Book book;

public void MainActivityViewModel (Context context)
{
this.context = context;
}


@Override
public void setModelData ()
{
book = new Book(); // update model class.
book.setName(x);
}

@Override
public Book getModelData ()
{
return book; //return the object to the view
}

}

关于android - 我们应该在哪里更新 MVVM 中的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56123061/

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