在包含布局的xml中使用onClick属性



我的项目有一个名为Welcome.kt 的类

class Welcome : AppCompatActivity() {
private lateinit var vb: ActivityWelcomesBinding
fun runDemo(v: View) {
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
vb = ActivityRegisterBinding.inflate(layoutInflater)
setContentView(vb.root)
}
}

在这个类的布局(Welcome.kt(中,我有通常的视图,还有一个包含的布局

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/background"
tools:context=".Welcome">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
...
...
<include layout="@layout/layout_buttons" />
...
...
</FrameLayout>
</ScrollView>
</FrameLayout>

这是包含的布局(layout_buttons(,一系列具有onClick属性的按钮,应该执行";startDemo";Welcome.kt 活动中的函数

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
...
...
<Button
android:id="@+id/btn_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
android:onClick="runDemo"
android:text="@string/text1" />
<Button
android:id="@+id/btn_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
android:onClick="runDemo"
android:text="@string/text2" />
<Button
android:id="@+id/btn_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
android:onClick="runDemo"
android:text="@string/text3" />
</LinearLayout>

由于按钮在包含的布局中,我找不到让它们调用"的方法;runDemo";Welcome.kt活动的功能。

我一直在寻找信息,但没有找到任何东西能解决我的问题。

提前感谢

您应该给include标记一个id,例如

<include id="@+id/buttonsLayout"
layout="@layout/layout_buttons" />

之后您可以这样使用它:

class Welcome : AppCompatActivity() {
private lateinit var vb: ActivityWelcomesBinding
fun runDemo(v: View) {
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
vb = ActivityRegisterBinding.inflate(layoutInflater)
setContentView(vb.root)
vb.buttonsLayout.yourBtnId

}
}

如果你仍然想在xml中使用onClick,那么你应该使用数据绑定,而不是视图绑定

最新更新