我使用过LiveData and ViewModel
示例,但我不了解此功能的用法,因为我可以在不使用此功能的情况下直接更改值,即使这是通过使用观察代码增加的代码行数,并且与ViewModel
通过创建MutableLiveData
.
下面的ViewModel
代码公共类 FirstViewModel 扩展了 ViewModel {
// Create a LiveData with a String
public MutableLiveData<String> mCurrentName;
public MutableLiveData<String> getCurrentName() {
if (mCurrentName == null) {
mCurrentName = new MutableLiveData<String>();
}
return mCurrentName;
}
}
在活动中使用
public class MainActivity extends AppCompatActivity {
private FirstViewModel mModel;
ActivityMainBinding mBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding=DataBindingUtil.setContentView(this,R.layout.activity_main);
// Get the ViewModel.
mModel= ViewModelProviders.of(this).get(FirstViewModel.class);
// Create the observer which updates the UI.
final Observer<String> nameObserver = new Observer<String>() {
@Override
public void onChanged(@Nullable final String newName) {
// Update the UI, in this case, a TextView.
mBinding.mNameTextView.setText(newName);
}
};
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
mModel.getCurrentName().observe(this, nameObserver);
mBinding.btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String anotherName = mBinding.etField.getText().toString();
mModel.getCurrentName().setValue(anotherName);
}
});
}
}
在ViewModel
与LiveData
Android的架构组件一起帮助创造生命周期感知应用程序。
ViewModel: ViewModel 类通常用于将视图逻辑(存在于 Activity 类中)与包含在 ViewModel 类中的业务逻辑显着分离。这种隔离是一种很好的架构设计,在维护大型项目时变得非常重要。
LiveData: LiveData 有助于以生命周期感知方式实现Observer Observable 模式。
在您的情况下,这可能看起来微不足道,因为您只是为 a 设置值TextView
。然而,考虑一些常见的场景,比如点击 api 来检索数据等。在这种情况下,ViewModel
负责提供要在 中显示的数据Activity
,当在 的帮助下完成时,LiveData
可以通过轻松确保生命周期意识来帮助避免崩溃。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句