根据官方文档,布局和绑定表达式,学习dataBinding,在布局中绑定事件,发现事件无效,在网上搜索了一些文章,是因为忘了写一段代码,记录一下
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="user"
type="com.hzj.jetpackkotlin.User" />
<variable
name="handlers"
type="com.hzj.jetpackkotlin.MyHandlers" />
</data>
<LinearLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.firstName}" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.lastName ?? user.firstName}"
android:onClick="@{handlers::onClickFriend}"/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮"
android:onClick="@{handlers::onClickFriend}"/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮"
android:onClick="@{()->handlers.onSaveClick(`哈哈`)}"/>
</LinearLayout>
</layout>
MainActivity
class MainActivity : AppCompatActivity() {
//private lateinit var binding:ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// binding = ActivityMainBinding.inflate(layoutInflater)
// val view = binding.root
// setContentView(view)
//textView.text="厉害"
// binding.textView.text="文本1"
// binding.button.setOnClickListener{
// }
/* val binding : ActivityMainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main)
binding.user = User("Test","User")*/
/* findViewById<TextView>(R.id.textView).apply {
textSize=20.0F
}*/
val binding : ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
binding.user= User("Test","User")
binding.handlers=MyHandlers()
}
}
binding.handlers=MyHandlers()
这一段代码,就是忘了写的,所以事件无效
class MyHandlers {
fun onClickFriend(view: View){
println("触发了事件")
}
fun onSaveClick(string:String){
println("触发了事件,参数是${string}")
}
}
data class User(val firstName:String,val lastName:String)