My problem is apparently simple, but could not find any simple and working solution on the web. I want to trigger an event with two parameters in a customized class (Fruit in the example below) and handle it in the MainActivity class. How is it done?
class Fruit @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
init {
inflate(context, R.layout.layout_fruit, this)
textViewOrange.setOnClickListener() {
// Trigger an event with two parameters (e.g. value: Int, text: String)
// after the user has clicked on textViewOrange
}
}
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// fruit.setOnEventListener () {
// Catch the event and get the two parameters
// created in Fruit class
// }
}
}
// activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layoutMain"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.example.android.alnus_event_test.Fruit
android:id="@+id/fruit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout_editor_absoluteX="56dp"
tools:layout_editor_absoluteY="134dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
// layout_fruit
<?xml version="1.0" encoding="utf-8"?>
<merge
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:parentTag="androidx.constraintlayout.widget.ConstraintLayout">
<TextView
android:id="@+id/textViewOrange"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:background="#82C7E6"
android:text="Orange"
android:textSize="30sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</merge>