Android开发经验谈Android技术知识Android开发

MVVM模式封装实践

2019-09-16  本文已影响0人  星星y

MVVM模式基于数据驱动UI,我们可以通过ViewModel很好的解藕ActivityView。相对于MVP模式PresenterView交互频繁,工程结构复杂,MVVM模式更加清晰简洁。有了DataBindingView层功能不再变得很弱,通过绑定属性/事件,可以布局文件中完成ViewModelView的交互。下面以Wandroid项目中的文章搜索功能来看看我对于MVVM模式的封装实践,也欢迎评论谈谈大家的看法。

项目地址

https://github.com/iamyours/Wandroid

DataBinding自定义属性与事件

新建一个CommonBindings.kt文件,用于处理DataBinding自定义属性/事件,这里添加搜索业务要用到的SmartRefreshLayoutEditTextBindingAdapter,代码如下

@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

我们将常用到的的属性和方法加入到BaseViewModel中,搜索具有分页功能,因此需要refreshingmoreLoading控制结束下拉刷新,加载更多,autoRefresh来控制SmartRefreshLayout自动刷新,hasMore控制是否还有更多,page控制分页请求,在mapPage方法中同意处理分页数据(刷新状态,是否更多)

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

然后创建SearchVM作为搜索业务的ViewModel

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用于数据交互

 <variable
    name="vm"
    type="io.github.iamyours.wandroid.ui.search.SearchVM"/>

然后在SmartRefreshLayout中绑定事件和属性

 <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属性,添加软键盘搜索事件

 <EditText
    ...
    android:text="@={vm.keyword}"
    android:imeOptions="actionSearch"
    app:searchAction="@{()->vm.search()}"
    />

完整布局如下:

<?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>

Activity中监听数据,更新ui

为了简化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

搜索最终效果

通过SearchActivitySearchVM,可以看到activity和view完全解耦,我们将业务逻辑放到ViewModel中,通过修改LiveData触发ui的变化。

搜索文章
上一篇 下一篇

猜你喜欢

热点阅读