如何使用databinding in kotlin
1.首先关键是配置好gradle:
in build.gradle(project):
ext.gradle_version = '3.0.1'
in build.gradle(app)
apply plugin: 'kotlin-kapt' android{ .... dataBinding{ enabled = true } } dependencies{ ... kapt "com.android.databinding:compiler:$gradle_version" }
//kapt "com.android.databinding:compiler:$gradle_version" 可以不用的
2.layout:
<layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <variable name="user" type="com.m.databindingdemo.model.User"/> </data> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{user.firstname}" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{user.lastname}" /> </LinearLayout> </layout>
3.User:(注意,field不能private,要不会读取不了)
class User( val firstname: String, val lastname: String)
4.activity:
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main) var user = User("Test", "User") binding.user = user }
相关推荐
hohohogetitup 2020-05-31
xuweinet 2019-06-21
NightWish 2018-06-13
hustpzb 2018-03-02
man0man 2018-01-18
Hens00 2017-03-02
wdd 2017-02-24
MatrixHero 2016-11-30
iqingfen 2017-02-27
稀土 2017-11-29