Wais Kamal
Wais Kamal

Reputation: 6200

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?

Upvotes: 1

Views: 2384

Answers (3)

Faz
Faz

Reputation: 354

Add in your oncreate method :

setOnClickListener(this)

and do as below :

public class MainActivity extends Appcomatactivity implements View.OnClickListner

Upvotes: 0

Kousalya
Kousalya

Reputation: 760

You need do like dis

ConstraintLayout parent = findViewById(R.id.parent);

parent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    
                }
            });

Upvotes: 1

Kiryl Tkach
Kiryl Tkach

Reputation: 3644

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.

Upvotes: 3

Related Questions