neo
neo

Reputation: 1404

Why it is not possible to use setOnClickListener directly for compound view?

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:

  1. Implement OnClickListener for your compound view
  2. Call setOnClickListener on init of your compound view
  3. 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()

    }


    }

Upvotes: 0

Views: 76

Answers (2)

Jaydeep chatrola
Jaydeep chatrola

Reputation: 2701

Make sure your are clicking on parent view.

it may not work if child view clickable and focusable are true

so try setting false for clickable and focusable on child view and then try

hope it helps..

Upvotes: 0

neo
neo

Reputation: 1404

I found some solution. Let the id of my compound view's root layout be called as root. If we set setOnClickListener as following:

myCompoundView.root.setOnClickListener {
     /// Handle here 
}

It magically works somehow.

Upvotes: 0

Related Questions