Ajay P. Prajapati Ajay P. Prajapati - 2 months ago 6
Java Question

Trigger an Action when ImageView is tapped three times in Specific time - Android

I have project in which I need to count touches on ImageView. If user touches the ImageView three times continuously, then trigger an action.

I have tried using

setOnTouchListener
, but couldn't find any method that can return an integer counter.

Here's abstract view of what I want to achieve:

if(touches == 3) {
//perform the action.
}


Can anyone tell me how can I count fingertouches on ImageView? Also if there's better approach, let me know.

Answer

Here you go mate plus code snippet

package com.pavneet.activitydemo.DB;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.pavneet.activitydemo.R;

/**
 * Created by Pavneet Singh on 20/06/16.
 */
public class TestA extends AppCompatActivity {

    private int i=0;
    private ImageView imageView;

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what==100){
                i=0;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_ab);
        imageView=(ImageView) findViewById(R.id.imageButtontest);

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (i==0){
                    ++i;
                    handler.sendEmptyMessageDelayed(100,3000); // 3000 equal 3sec , you can set your own limit of secs
                }else if(i==2){
                    Toast.makeText(TestA.this, "Three Touch Clicked" , Toast.LENGTH_SHORT).show();
                    i=0;
                    handler.removeMessages(100);
                }else
                    ++i;
            }
        });

    }
}

Layout Code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_margin="16dp"
    android:layout_height="match_parent">
<ImageView
    android:src="@mipmap/ic_launcher"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageButtontest"
        android:layout_gravity="center_horizontal" />
</LinearLayout>