kotlin+mvvm+databinding+recyclerview
上一篇讲了一般kotlin的recyclereview的写法,这次来整合databinging跟MVVM。
首先是xml(主画面)
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
tools:listitem="@layout/item_view"
tools:itemCount="5" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
再来是item_view的xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="Post"
type="com.example.myapplication.Post" />
<variable
name="listener"
type="com.example.myapplication.Listener" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:padding="5dp"
android:textSize="16sp"
android:text="@{Post.post}"
android:onClick="@{()-> listener.onClick(Post)}"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
今天主要先说Activity的部分
class Activity:AppCompatActivity() {
lateinit var binding: ActivityMainBinding
private val mViewModel by lazy {
initViewModel(application, ViewModel::class.java)
}
private val mAdapter by lazy {
Adapter<Post>(
R.layout.item_view,
listener = object : Listener<Post> {
override fun onClick(post: Post) {
Toast.makeText(this@Activity, post.post, Toast.LENGTH_SHORT).show()
}
}
)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.recyclerView.adapter = mAdapter
mViewModel.data.observe(this, Observer { post ->
mAdapter.updateData(post)
})
mViewModel.fetchData()
}
}
这边的lazy是让程序执行时,需要的时後在读取,可以提升程序执行速度及记忆体空间的利用
listener是我自定义onclick的interface
因为後面的viewmodel是继承androidviewmodel,所以我用一个扩展含式,去取的程序的application的上下文,也可以直接在manifests里面新增
前言 这个演讲蛮general的,也适合任何leader来看看。如果你觉得team里面的人都不太爱...
何时会使用到HTTP Method 一般用户开启浏览器时,例如:开启chrome时,会由特定网址导向...
大家都知道Google断线时会有小恐龙的离线游戏, 以前第一次看到的时候超惊喜!(我到现在断线的时候...
知道什麽是自动测试之後,我们来看看怎麽进行和资料库互动的自动测试。 测试目标 假设我们现有的资料关联...
JavaScript 是可插入 HTML 页面的编程代码,插入 HTML 页面后,可由所有的现代浏览...