I have simple compound view with ConstraintLayout
as a root. Attributes like clickable
, focusable
are enabled. It is perfectly shown on my layout. I want to handle when it gets clicked. Approach is simple, but it does not work:
myCompoundView.setOnClickListener {
/// Handle click here
}
But that callback is not called at all. I really don't understand why it refuses to be called. Another approach would be following:
- Implement OnClickListener for your compound view
- Call
setOnClickListener
oninit
of your compound view - Create your own callback and use it when
onClick
gets called
But this approach requires more code and it just implements what already made. Possibly, callback can become null at some point. So, my question is why simple setOnClickListener
does not work? If it does not work, how to be notified when my compound view gets clicked?
There is a code if you need:
/// my compound view below
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://sch`enter code here`emas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:clickable="true"
android:focusable="true"
android:id="@+id/root"
android:background="?attr/selectableItemBackground"
>
/// some views here
</androidx.constraintlayout.widget.ConstraintLayout>
Here is how I use it:
<sample.sample.com.ChooserView
android:id="@+id/familyStateChooserView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:chooseLabel="@string/family_kind"
android:layout_marginTop="8dp"
/>
Here is its class:
class ChooserView(
context: Context,
attrs: AttributeSet
) : ConstraintLayout(context, attrs) {
init {
LayoutInflater.from(context)
.inflate(R.layout.chooser_view, this, true)
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ChooserView, 0, 0)
label.text = typedArray.getString(R.styleable.ChooserView_chooseLabel)
typedArray.recycle()
}
}