android - 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。
解决方案
您正在调用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()}"/>
推荐阅读
- intellij-idea - IntelliJ IDEA CE for 和 FTC Robotics Simulator 中的导入问题
- c++ - 错误:为参数 2 提供了默认参数
- r - 我想将数据分成两个数据集:一个训练数据集和一个测试数据集。(R中的时间序列分析)
- gn - 如何构建树外 Fuchsia OS 程序
- python - Django拦截将对象添加到多对多字段
- python - Python:检测文本块并将其从图像中删除(OpenCV)
- authentication - 带有过期 JWT 刷新令牌的滑动窗口
- google-analytics - 这可能吗?谷歌分析访问
- xamarin.ios - 如何在 xamarin iOS 中集成两个应用程序?
- pandas - 垂直连接 2 个数据帧,中间为空行