首页 > 解决方案 > android:onClick 属性不能通过数据绑定工作

问题描述

这是我的片段类代码。

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

标签: androidkotlinandroid-databinding

解决方案


您正在调用clickable.onClicking()尚未设置的 xml。当您实例化一个数据绑定对象时,您可能还必须设置它的变量(就像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()}"/>


推荐阅读