在app build.gradle开启databinding 和 bindingAdapter
// DataBinding开启 启用中
buildFeatures {
dataBinding = true
}
// 支持 bindingAdapter
apply plugin: "kotlin-kapt"
kapt {
generateStubs = true
}
创建UserRepository ,用来请求网络拿数据,或者从数据库中拿数据
class Repository private constructor(){
companion object{
val mUserRepository = UserRepositoryHolder.holder
}
private object UserRepositoryHolder {
val holder = Repository()
}
fun getArticles(listenner:onLoadArticleListenner){
HttpClient.instance.instanceRetrofit(WanAndroidApi::class.java)
.getArticles(1)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : ResponseObserve<ArticleResponse>() {
override fun success(data: ArticleResponse?) {
data?.let { listenner.loadSuccess(it) }
}
override fun failure(errorMsg: String?) {
errorMsg?.let { listenner.loadError(it) }
}
})
}
interface onLoadArticleListenner{
fun loadSuccess(data:ArticleResponse);
fun loadError(msg:String)
}
}
创建viewmodel 支持屏幕旋转数据能维持,和同个activity 里面的fragment 能够数据共享
class ArticleListViewModel : ViewModel() {
var articles: MutableLiveData<List<Article>>? = null
var loaddingLiveData: MutableLiveData<Boolean>? = null
init {
articles = MutableLiveData()
loaddingLiveData = MutableLiveData()
}
fun getArticles() {
loaddingLiveData?.value = true
UserRepository.mUserRepository.getArticles(object : UserRepository.onLoadArticleListenner {
override fun loadSuccess(data: ArticleResponse) {
loaddingLiveData?.value = false
articles?.setValue(data.datas);
}
override fun loadError(msg: String) {
loaddingLiveData?.value = false
articles?.setValue(null);
}
})
}
}
activity布局 并引入前面创建的viewmodel
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:bind="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="mv"
type="com.amn.jetpackmvvm.test.ArticleListViewModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.scwang.smartrefresh.layout.SmartRefreshLayout
android:id="@+id/homeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/collectRecycleView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.scwang.smartrefresh.layout.SmartRefreshLayout>
</LinearLayout>
</layout>
在activity 绑定布局,和获取viewmodel并且设置viewmodel (在布局引入viewmodel 后 databinding才会有设置viewmodel 方法)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//databinding 绑定布局
articlelistBinding =
DataBindingUtil.setContentView<ActivityArticleListBinding>(this, activity_article_list)
articlelistBinding?.lifecycleOwner = this
//获取viewmodel
artcleViewModel = ViewModelProvider(this).get(ArticleListViewModel::class.java);
//databinding 和viewmodel 绑定
articlelistBinding?.mv = artcleViewModel
}
目前这个和activity 绑定的viewmodel 暂没用到,后面可用来跟新刷新状态,或者可用bindingAdapter 绑定刷新和加载更多事件
接下来 recycleview 的设置,因在viewmodel 采用livedata 可用来数据双向绑定,这里只是单项,在activity中 监听 数据变化,设置对应的adapter 数据
private fun observeLivaData() {
artcleViewModel?.loaddingLiveData?.observe(this, Observer {
if (!it) {
articlelistBinding?.homeRefreshLayout?.finishRefresh()
}
})
artcleViewModel?.articles?.observe(this, Observer {
articleAdapter?.setData(it)
})
}
在adapter中
class ArticleAdapter(context: Context) : Adapter<ArticleAdapter.ArticleViewHolder>() {
var datas: ArrayList<Article>? = ArrayList()
val context: Context = context
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleViewHolder {
val inflate = DataBindingUtil.inflate<ItemArticleBinding>(
LayoutInflater.from(context),
R.layout.item_article,
parent,
false
)
return ArticleViewHolder(inflate.root)
}
override fun getItemCount(): Int {
return (if (datas == null) 0 else datas?.size)!!
}
override fun onBindViewHolder(holder: ArticleViewHolder, position: Int) {
val article = datas?.get(position)
val binding = DataBindingUtil.getBinding<ItemArticleBinding>(holder.itemView);
binding?.itemArticle = article
binding?.executePendingBindings()
}
fun setData(articles: List<Article>) {
datas?.clear()
datas?.addAll(articles)
notifyDataSetChanged()
}
class ArticleViewHolder(itemView: View) : ViewHolder(itemView) {
}
}
databinding ,livedata,viewmodel 基础使用就到这里了,有空后面还会加room 以及他们更多用法