Data Binding per Activity e/o RecyclerView ( kotlin )
data class Item( val name: String, val age: String )
/*
* aggiusta build.gracle
* make project cmd + F9
* edita activity sia xml che classe
* make project cmd + F9
* leggi su:
* https://developer.android.com/topic/libraries/data-binding/index.html
* https://proandroiddev.com/modern-android-development-with-kotlin-september-2017-part-1-f976483f7bd6
*
* Questo è un esempio di Activity, AdapterExample contiene un esempio per adapter di RecyclerView
* */
class Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
// aggiorna una view
binding.mytextView.text = "Hello there"
binding.executePendingBindings()
// aggiorna una serie di view
binding.apply {
mytextView.text = "Hello there"
anotherTextView.text = "42"
}.executePendingBindings()
// bind di un oggetto
Handler().postDelayed({
val item: Item = Item("marco", "18")
binding.myvariable = item
binding.executePendingBindings()
}, 3000)
}
}
class AdapterExample(val items: List<Item>): RecyclerView.Adapter<AdapterExample.ViewHolder>() {
lateinit var binding: LayoutRowBinding
override fun getItemCount(): Int = items.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder{
binding = DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.launcher_row, parent, false)
return ViewHolder(binding.root)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.get( items[position] )
}
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun get(item: Item) {
binding.campaign = item
binding.executePendingBindings()
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="myvariable"
type="io.github.mpao.example.Item"
/>
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/mytextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:padding="16dp"
android:textSize="30sp"
android:text="@{myvariable.name}"
tools:text="Messaggio in arrivo"/>
<TextView
android:id="@+id/anotherTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/mytextView"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="@{myvariable.age}"
android:textSize="30sp"/>
</RelativeLayout>
</layout>
...
apply plugin: 'kotlin-kapt'
android {
...
dataBinding.enabled = true
}
kapt {
generateStubs = true
}
dependencies {
...
// databinding
kapt "com.android.databinding:compiler:3.0.0-beta6"
}