Issue
My project has a class called 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)
}
}
In the layout of this class (Welcome.kt) I have the usual views and also an included layout
<?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>
And this is the included layout (layout_buttons), a series of buttons that have the onClick attribute, which should execute the "startDemo" function that is in the activity 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>
Since the buttons are inside an included layout, I can't find a way to get them to call the "runDemo" function of the Welcome.kt activity.
I have searched for information but nothing I have found has solved my problem.
Thanks in advance
Solution
you should give your include tag an id for example
<include id="@+id/buttonsLayout"
layout="@layout/layout_buttons" />
After this you can use it like this :
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
}
}
if you want still to use onClick in the xml then you should use data binding not view binding
Answered By - Mohmmaed-Amleh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.