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

android:onClick attribute is not working through data binding

这是我的片段代码 class。

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()

    }
}

这是我的片段代码 XML。

<?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 没有显示任何 Toast 结果。按下按钮没有任何反应。我可以通过在 Fragment class 中的按钮 ID 上设置 onClickListener 来显示吐司,但无法使用数据绑定通过 XML 中的 onClick 属性显示吐司。

您正在 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()}"/>