MVVM
模式基于数据驱动UI,咱们能够经过ViewModel
很好的解藕Activity
与View
。相对于MVP
模式Presenter
与View
交互频繁,工程结构复杂,MVVM
模式更加清晰简洁。有了DataBinding
,View
层功能再也不变得很弱,经过绑定属性/事件,能够布局文件中完成ViewModel
与View
的交互。下面以Wandroid项目中的文章搜索
功能来看看我对于MVVM
模式的封装实践,也欢迎评论谈谈你们的见解。php
新建一个CommonBindings.kt
文件,用于处理DataBinding自定义属性/事件,这里添加搜索业务要用到的SmartRefreshLayout和EditText
的BindingAdapter
,代码以下android
@BindingAdapter( value = ["refreshing", "moreLoading", "hasMore"], requireAll = false )
fun bindSmartRefreshLayout( smartLayout: SmartRefreshLayout, refreshing: Boolean, moreLoading: Boolean, hasMore: Boolean ) {//状态绑定,控制中止刷新
if (!refreshing) smartLayout.finishRefresh()
if (!moreLoading) smartLayout.finishLoadMore()
smartLayout.setEnableLoadMore(hasMore)
}
@BindingAdapter( value = ["autoRefresh"] )
fun bindSmartRefreshLayout( smartLayout: SmartRefreshLayout, autoRefresh: Boolean ) {//控制自动刷新
if (autoRefresh) smartLayout.autoRefresh()
}
@BindingAdapter(//下拉刷新,加载更多 value = ["onRefreshListener", "onLoadMoreListener"], requireAll = false )
fun bindListener( smartLayout: SmartRefreshLayout, refreshListener: OnRefreshListener?, loadMoreListener: OnLoadMoreListener? ) {
smartLayout.setOnRefreshListener(refreshListener)
smartLayout.setOnLoadMoreListener(loadMoreListener)
}
//绑定软键盘搜索
@BindingAdapter(value = ["searchAction"])
fun bindSearch(et: EditText, callback: () -> Unit) {
et.setOnEditorActionListener { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
callback()
et.hideKeyboard()
}
true
}
}
复制代码
咱们将经常使用到的的属性和方法加入到BaseViewModel
中,搜索具备分页功能,所以须要refreshing
和moreLoading
控制结束下拉刷新,加载更多,autoRefresh
来控制SmartRefreshLayout自动刷新,hasMore
控制是否还有更多,page
控制分页请求,在mapPage
方法中赞成处理分页数据(刷新状态,是否更多)git
open class BaseViewModel : ViewModel() {
protected val api = WanApi.get()
protected val page = MutableLiveData<Int>()
val refreshing = MutableLiveData<Boolean>()
val moreLoading = MutableLiveData<Boolean>()
val hasMore = MutableLiveData<Boolean>()
val autoRefresh = MutableLiveData<Boolean>()//SmartRefreshLayout自动刷新标记
fun loadMore() {
page.value = (page.value ?: 0) + 1
moreLoading.value = true
}
fun autoRefresh() {
autoRefresh.value = true
}
open fun refresh() {//有些接口第一页可能为1,因此要重写
page.value = 0
refreshing.value = true
}
/** * 处理分页数据 */
fun <T> mapPage(source: LiveData<ApiResponse<PageVO<T>>>): LiveData<PageVO<T>> {
return Transformations.map(source) {
refreshing.value = false
moreLoading.value = false
hasMore.value = !(it?.data?.over ?: false)
it.data
}
}
}
复制代码
而后建立SearchVM
做为搜索业务的ViewModel
github
class SearchVM : BaseViewModel() {
val keyword = MutableLiveData<String>()
//类型为LiveData<ApiResponse<PageVO<ArticleVO>>>
private val _articlePage = Transformations.switchMap(page) {
api.searchArticlePage(it, keyword.value ?: "")
}
//类型LiveData<PageVO<ArticleVO>>
val articlePage = mapPage(_articlePage)
fun search() {//搜索数据
autoRefresh()
}
}
复制代码
以前已经添加了DataBinding
的自定义属性/事件,咱们如今在布局中使用它。 先添加SearchVM
用于数据交互api
<variable name="vm" type="io.github.iamyours.wandroid.ui.search.SearchVM"/>
复制代码
而后在SmartRefreshLayout
中绑定事件和属性bash
<com.scwang.smartrefresh.layout.SmartRefreshLayout ... app:onRefreshListener="@{()->vm.refresh()}" app:refreshing="@{vm.refreshing}" app:moreLoading="@{vm.moreLoading}" app:hasMore="@{vm.hasMore}" app:autoRefresh="@{vm.autoRefresh}" app:onLoadMoreListener="@{()->vm.loadMore()}">
复制代码
在EditText
中双向绑定keyword
属性,添加软键盘搜索事件app
<EditText ... android:text="@={vm.keyword}" android:imeOptions="actionSearch" app:searchAction="@{()->vm.search()}" />
复制代码
完整布局以下:ide
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable name="vm" type="io.github.iamyours.wandroid.ui.search.SearchVM"/>
</data>
<LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
<RelativeLayout android:layout_width="match_parent" android:layout_height="48dp">
<TextView android:id="@+id/tv_cancel" android:layout_width="wrap_content" android:layout_height="match_parent" android:textSize="14sp" android:layout_marginRight="10dp" android:gravity="center" android:textColor="@color/text_color" android:layout_alignParentRight="true" android:text="取消" app:back="@{true}" />
<EditText android:layout_width="match_parent" android:layout_height="40dp" android:layout_toLeftOf="@id/tv_cancel" android:lines="1" android:layout_marginRight="10dp" android:inputType="text" android:paddingLeft="40dp" android:hint="搜索关键词以空格隔开" android:layout_centerVertical="true" android:textSize="14sp" android:layout_marginLeft="10dp" android:textColor="@color/title_color" android:textColorHint="@color/text_color" android:background="@drawable/bg_search" android:text="@={vm.keyword}" android:imeOptions="actionSearch" app:searchAction="@{()->vm.search()}" />
<ImageView android:id="@+id/iv_search" android:layout_width="48dp" android:layout_height="48dp" android:tint="@color/text_color" android:src="@drawable/ic_search" android:padding="13dp" android:layout_marginLeft="10dp" />
</RelativeLayout>
<View android:layout_width="match_parent" android:layout_height="1px" android:background="@color/divider" />
<com.scwang.smartrefresh.layout.SmartRefreshLayout android:id="@+id/refreshLayout" android:layout_width="match_parent" app:onRefreshListener="@{()->vm.refresh()}" app:refreshing="@{vm.refreshing}" app:moreLoading="@{vm.moreLoading}" app:hasMore="@{vm.hasMore}" app:autoRefresh="@{vm.autoRefresh}" android:background="@color/bg_dark" app:onLoadMoreListener="@{()->vm.loadMore()}" android:layout_height="match_parent">
<com.scwang.smartrefresh.layout.header.ClassicsHeader android:layout_width="match_parent" app:srlAccentColor="@color/text_color" app:srlPrimaryColor="@color/bg_dark" android:layout_height="wrap_content"/>
<androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView" android:overScrollMode="never" tools:listitem="@layout/item_qa" android:layout_width="match_parent" android:layout_height="match_parent"/>
<com.scwang.smartrefresh.layout.footer.ClassicsFooter android:layout_width="match_parent" app:srlAccentColor="@color/text_color" app:srlPrimaryColor="@color/bg_dark" android:layout_height="wrap_content"/>
</com.scwang.smartrefresh.layout.SmartRefreshLayout>
</LinearLayout>
</layout>
复制代码
为了简化ViewModel
的建立,新建FragmentActivity
的扩展函数,见Lazy.kt,每次以lazy
形式初始化。函数
inline fun <reified T : ViewModel> FragmentActivity.viewModel() =
lazy { ViewModelProviders.of(this).get(T::class.java) }
复制代码
建立BaseActivity
open abstract class BaseActivity<T : ViewDataBinding> : AppCompatActivity() {
abstract val layoutId: Int
lateinit var binding: T
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, layoutId)
binding.lifecycleOwner = this
}
}
复制代码
而后新建SearchActivity
,完成最后一步
class SearchActivity : BaseActivity<ActivitySearchBinding>() {
override val layoutId: Int
get() = R.layout.activity_search
val vm by viewModel<SearchVM>()
val adapter = ArticleAdapter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding.vm = vm
initRecyclerView()
}
private fun initRecyclerView() {
binding.recyclerView.also {
it.adapter = adapter
it.layoutManager = LinearLayoutManager(this)
}
vm.articlePage.observe(this, Observer {
adapter.addAll(it.datas, it.curPage == 1)
})
}
}
复制代码
关于Adapter的封装见这里DataBoundAdapter
经过SearchActivity
和SearchVM
,能够看到activity和view彻底解耦,咱们将业务逻辑放到ViewModel
中,经过修改LiveData
触发ui的变化。