Search code examples
androidonclicklistenerandroid-constraintlayout

ConstraintLayout not handling clicks


I have an empty ConstraintLayout (which I am using as an overlay) inside a FrameLayout:

<FrameLayout 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:context=".ui.home.HomeFragment">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/overlay"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#80000000"
        android:clickable="true"
        android:focusable="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

</FrameLayout>

To which I have attached an event listener:

public class HomeFragment extends Fragment implements View.OnClickListener {
    ...
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.overlay:
                // Do something
                break;
        }
    }
}

The problem is that when the overlay is clicked, Some code here is not getting executed. Removing android:clickable and android:focusable doesn't help. Is there any workaround for this problem?


Solution

  • findViewById(R.id.overlay).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        //Do something
        }
    }
    

    This will do the work. I don't see in your code where you actually set onclicklistener to your overlay view.