使用 MVVM 重用组件的最佳实践
Best practice reusing components with MVVM
我想知道是否有人找到了一些在使用 MVVM 时重用组件(多视图)的巧妙解决方案。
组件 我的意思是一组最终在应用程序中重复使用的视图。
例如,由 ImageView
和 TextView
组成的空状态,为了示例,我们还为文本添加某种 ClickListener
。
现在,我想做的是在多个 .xml 文件中重用此视图,但为文本、图像提供不同的值,并将侦听器绑定到片段中的操作 ViewModel
.
我一直在做的是创建一个 CustomEmptyState
来扩展 LinearLayout
或某种布局并向其添加 Custom Attributes
。
所以,最后,我会像这样使用我的自定义视图:
<com.whatever.customViews.CutomEmptyState
app:image="@drawable/someImage"
app:text="@string/empty_text"
app:onTextClicked="@{viewModel.onEmptyStateClicked()}" />
我的问题是,对此有不同的方法吗?一个更好的?我不喜欢的是用 <declare-styleable>
编写自定义属性,因为那时我必须跟踪 3 个文件:
- 基础视图的
.xml
布局
- 视图的
.java/.kt
具有处理属性的样板代码
<declare-styleable>
具有全部属性
有没有办法把2和3结合起来?
比如说,你必须显示一些你确定会被数据绑定的文本值。
那么,如果你对值进行数据绑定,那么有一种方法,但不是一种优雅的方法。
在自定义视图中声明一个变量,例如:private var status = ""
然后写一个setter函数:
fun setStatus(status: String) {
this.status = status
//refresh your views based on value or set this to the text view
}
然后像这样进行数据绑定:
app:status="@{viewModel.status}"
这样您就不需要再声明样式了
<com.whatever.customViews.CutomEmptyState
app:image="@drawable/someImage"
app:text="@string/empty_text"
app:onTextClicked="@{viewModel::onEmptyStateClicked}" />
public void onEmptyStateClicked(View view){
your code
}
我想知道是否有人找到了一些在使用 MVVM 时重用组件(多视图)的巧妙解决方案。
组件 我的意思是一组最终在应用程序中重复使用的视图。
例如,由 ImageView
和 TextView
组成的空状态,为了示例,我们还为文本添加某种 ClickListener
。
现在,我想做的是在多个 .xml 文件中重用此视图,但为文本、图像提供不同的值,并将侦听器绑定到片段中的操作 ViewModel
.
我一直在做的是创建一个 CustomEmptyState
来扩展 LinearLayout
或某种布局并向其添加 Custom Attributes
。
所以,最后,我会像这样使用我的自定义视图:
<com.whatever.customViews.CutomEmptyState
app:image="@drawable/someImage"
app:text="@string/empty_text"
app:onTextClicked="@{viewModel.onEmptyStateClicked()}" />
我的问题是,对此有不同的方法吗?一个更好的?我不喜欢的是用 <declare-styleable>
编写自定义属性,因为那时我必须跟踪 3 个文件:
- 基础视图的
.xml
布局 - 视图的
.java/.kt
具有处理属性的样板代码 <declare-styleable>
具有全部属性
有没有办法把2和3结合起来?
比如说,你必须显示一些你确定会被数据绑定的文本值。
那么,如果你对值进行数据绑定,那么有一种方法,但不是一种优雅的方法。
在自定义视图中声明一个变量,例如:private var status = ""
然后写一个setter函数:
fun setStatus(status: String) {
this.status = status
//refresh your views based on value or set this to the text view
}
然后像这样进行数据绑定:
app:status="@{viewModel.status}"
这样您就不需要再声明样式了
<com.whatever.customViews.CutomEmptyState
app:image="@drawable/someImage"
app:text="@string/empty_text"
app:onTextClicked="@{viewModel::onEmptyStateClicked}" />
public void onEmptyStateClicked(View view){
your code
}