Issue
So I'd like to make a function that changes the tint of the view that is calling the function.
I'm pretty sure I got the tint part down I'm just not quite sure how or where I need to define this function so that I can either select it as the onClick method in the built-in properties menu or I can reference it in the xml file(preferably the former).
Right now I have the function in the MainActivity.kt file inside the class and I selected the function on all the different views in the properties menu but when I run the app and actually click on of these views I get a crash saying "Could not find method in parent or ancestor Context for android:onClick attribute"
I would really appreciate some help with this, thanks in advance!
Solution
You can set the same on click listener to multiple views.
val tintChanger = View.OnClickListener { view ->
println("View with id=${view.id} clicked")
changeTintOf(view as ImageView)
}
imageViewOne.setOnClickListener(tintChanger)
imageViewTwo.setOnClickListener(tintChanger)
imageViewThree.setOnClickListener(tintChanger)
How to set on click listener to views without knowing their ids?
val imageContainerLayout = findViewById<LinearLayout>(R.id.imageContainer)
// val imageContainerLayout = binding.imageContainer
imageContainerLayout.children.forEach {
it.setOnClickListener(tintChanger)
}
// xml
<LinearLayout
android:id="@+id/imageContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<ImageView ... /> // without android:id set
<ImageView ... /> // without android:id set
<ImageView ... /> // without android:id set
</LinearLayout>
Not preferred way nowadays but if you want to set a click listener on your view by xml, your activity should contain a public method changeTintOnClick
with an argument view: View
.
// MainActivity.kt
fun changeTintOnClick(view: View) {
println("View click listener set by XML")
println("View clickView with id=${view.id} clicked")
changeTintOf(view as ImageView)
}
private fun changeTintOf(view: ImageView) {
// your implementation for tint
}
<ImageView ...
android:onClick="changeTintOnClick"
/>
Answered By - ocos
Answer Checked By - David Marino (JavaFixing Volunteer)