android:onClick属性无法通过数据绑定工作



这是Fragment类的代码。

class FragmentOne : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
// return inflater.inflate(R.layout.fragment_one, container, false)
val binding: FragmentOneBinding =
DataBindingUtil.inflate(inflater, R.layout.fragment_one, container, false)
return binding.root
}
fun onClicking(){
Toast.makeText(activity, "You clicked me.", Toast.LENGTH_SHORT).show()
}
}

这是我的FragmentXML代码。

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".FragmentOne">
<data>
<variable
name="clickable"
type="com.example.fragmentpractise1.FragmentOne" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hola Gola"
android:layout_marginTop="40dp"
android:onClick="@{()-> clickable.onClicking()}"/>
</LinearLayout>
</layout>

现在我试图理解的是,为什么android:onClick没有显示任何吐司结果。按下按钮后什么也没发生。我可以通过在Fragment类中的按钮id上设置onClickListener来显示toast,但不能通过使用数据绑定的XML中的onClick属性来显示toast。

您正在xml中调用尚未设置的clickable.onClicking()。当您实例化一个数据绑定对象时,您可能还需要设置它的变量(如示例中的clickable(

在实例化后设置该变量,如


override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
// return inflater.inflate(R.layout.fragment_one, container, false)
val binding: FragmentOneBinding =
DataBindingUtil.inflate(inflater, R.layout.fragment_one, container, false)
binding.clickable = this // your fragment
return binding.root
}

此外,在onClick中使用v而不是()更合理,因为这是Java语法中接收一个视图参数的lambda。为了提高的可读性,我建议将其更改为以下内容

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hola Gola"
android:layout_marginTop="40dp"
android:onClick="@{ v -> clickable.onClicking()}"/>