Search code examples
javaandroidonclicklistenerontouchlistener

OnClickListener to be executed only once


On an image, I want to set a click listener in order to performe an action after a click.

The code below is called more than once even after one click.

How can I prevent that? (I have used either an onTouchListener but the result was the same...)

   Image1.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            Log.d("DisplayImage", "on click");
            DisplayOneImage doi=new DisplayOneImage(DisplayImage.this,"Filtered image 1");
            doi.show();
        }
    });

The xml file:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/scrollView1"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"

>

<LinearLayout

    android:orientation="vertical"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    >

    <!-- \/ \/ \/ \/ To be deleted Menu \/ \/ \/ \/ -->
    <!--include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" /-->
    <!-- /\ /\ /\ /\ To be deleted Menu /\ /\ /\ /\  -->

    <LinearLayout
        android:id="@+id/img_original"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:padding="10dp"
        android:layout_weight="1">


        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Original Image:" />

        <ImageView
            android:id="@+id/initial_photo"

            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"/>

        </ImageView>

    </LinearLayout>
</ScrollView>

Solution

  • I'd set the OnClickListener to null inside the onClick method -as follows.

      Image1.setOnClickListener(new View.OnClickListener() {
    
        public void onClick(View v) {
            Log.d("DisplayImage", "on click");
            DisplayOneImage doi=new DisplayOneImage(DisplayImage.this,"Filtered image 1");
            doi.show();
            v.setOnClickListener(null);//Remove setOnClickListener
        }
    });