[英]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
沒有顯示任何吐司結果。 按下按鈕沒有任何反應。 我可以通過在片段 class 中的按鈕 ID 上設置onClickListener
來顯示 toast,但無法使用數據綁定通過onClick
中的 onClick 屬性顯示 toast。
您在 xml 中調用clickable.onClicking()
,但尚未設置。 當您實例化數據綁定 object 時,您可能還必須設置其變量(如示例中的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()}"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.