liuhedev 2018-02-03
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 }