Double tap android java

Implement double click for button in Android

I recommend switching to a more native way like long press (answer to linked question) or something more creative (using multi-touch), unless you are bent on the Windows default double-click way of doing things?

You may have a valid reason though — double clicking is after all faster than long press.

I wrote this for popping up a Toast message on a double click in a mapping application:

private long lastTouchTime = -1; @Override public boolean onTouchEvent(MotionEvent e, MapView mapView) < GeoPoint p = null; if (e.getAction() == MotionEvent.ACTION_DOWN) < long thisTime = System.currentTimeMillis(); if (thisTime - lastTouchTime < 250) < // Double click p = mapView.getProjection().fromPixels((int) e.getX(), (int) e.getY()); lastTouchTime = -1; >else < // too slow lastTouchTime = thisTime; >> if (p != null) < showClickedLocation(p);// Raise a Toast >return false; > 

This is a good site for performing double click. I used it and worked.

public class DoubleClickTest extends Activity < String TAG = "DoubleOrSingleClickTest"; private boolean waitDouble = true; private static final int DOUBLE_CLICK_TIME = 350; // double click timer @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.double_click_test); Button button = (Button) findViewById(R.id.buttonDoubleOrSingleClicked); button.setOnClickListener(listenerDoubleOrSingle); >View.OnClickListener listenerDoubleOrSingle = new View.OnClickListener() < @Override public void onClick(View v) < if (waitDouble == true) < waitDouble = false; Thread thread = new Thread() < @Override public void run() < try < sleep(DOUBLE_CLICK_TIME); if (waitDouble == false) < waitDouble = true; singleClick(); >> catch (InterruptedException e) < e.printStackTrace(); >> >; thread.start(); > else < waitDouble = true; doubleClick(); >> >; // single event private void singleClick() < Log.i(TAG, "singleClick"); >// double event private void doubleClick() < Log.i(TAG, "doubleClick"); >> 

Create your own DoubleTapListener

You can create a DoubleTapListener by inheriting View.OnClickListener and adding a Callback of your listener.

MyDoubleClickListener.class

public class MyDoubleClickListener implements View.OnClickListener < private boolean isRunning= false; private int resetInTime =500; private int counter=0; private DoubleClickCallback listener; public DoubleTapListener(Context context) < listener = (DoubleClickCallback)context; >@Override public void onClick(View v) < if(isRunning) < if(counter==1) //counter++; if(!isRunning) < isRunning=true; new Thread(new Runnable() < @Override public void run() < try < Thread.sleep(resetInTime); isRunning = false; counter=0; >catch (InterruptedException e) < e.printStackTrace(); >> >).start(); > > > 

DoubleClickCallback.class

public interface DoubleClickCallback

And you are done. You can use this Listener in any Activity.

How do I use this DoubleClickListener in my Activity?

Implement Callback in your activity and override the method.

public class MainActivity extends AppCompatActivity implements MyDoubleClickListener < private Button button; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button)findViewById(R.id.button); button.setOnClickListener(new DoubleTapListener(this)); //@Override public void onDoubleClick(View v) < // Toast to show double click >> 

Important point is using this concept you can create any kind of listener (Triple-click listener)

See the full working code HERE

Источник

how to implement double click in android [duplicate]

Why dont you use Long Press event insted while its Recommanded UI. Read Answer Here , I strongly recommand to use this.

Or if its anyhow you want to implement you have two options , one is this using boolean and second is using Gesture Listener.

Читайте также:  Biggest project in python

I feel this answer may be dated now. Double clicking is a common interaction on desktop layouts, and while Android isn’t a desktop os, ChromeOS is, and now supports Android apps, so whether or not we should be using double-click may vary situation to situation. Long pressing with a mouse is going to be bad UX.

Another reason to agree with @JediBurrell is for consistency for a given app. We’re just porting our Win/iOS/OSX app to Android. Our users are used to double-tapping to take a certain action, and it would be very odd to make Android the only platform where they have to long-press instead.

It is hold, but,for new readers, I made a small library to simplify this kind of stuff, check this article: Double click listener on android.

The library is very small, and here is the GitHub Repository Link.

And you will just use it like this:

Button btn = new Button(this); btn.setOnClickListener( new DoubleClick(new DoubleClickListener() < @Override public void onSingleClick(View view) < // Single tap here. >@Override public void onDoubleClick(View view) < // Double tap here. >>); 

you can use on long click instead of using double click by override this method

 abstract boolean onLongClick(View v) 

Called when a view has been clicked and held.

You may employ RxAndroid in that case in Kotlin it shall be like this:

yourView.clicks().buffer(500, TimeUnit.MILLISECONDS, 2).filter < it.size >= 2 >.subscribe < // Handle double click >
  1. We apply clicks() extension function on a given view which creates an RX observable sequence.
  2. We tell RX to emit an event after either 500 ms or 2 consecutive clicks take place within 500 ms.
  3. We tell RX to take only the events only with 2 consecutive click
  4. Last but not least we subscribe to the event sequence which is our DoubleClick handler

Try the below modified code::

//Check that thisTime is greater than prevTime //just incase system clock reset to zero static prevTime = 0; thisTime = Calendar.getInstance().getTimeInMillis(); if(prevTime < thisTime) < //Check if times are within our max delay if((thisTime - prevTime) else < //Otherwise Reset firstTap firstTap = true; >> else

I did a simple solution like that —

buttonTab.setOnClickListener(new View.OnClickListener() < int count = 0; Handler handler = new Handler(); Runnable runnable = () ->count = 0; @Override public void onClick(View v) < if (!handler.hasCallbacks(runnable)) handler.postDelayed(runnable, 500); if(count==2)< /*View is double clicked.Now code here.*/ >> >); 

I have Implemented the code on which the Background color and text color changes on clicking the screen twice(Double Tap) here is the code.

 int i = 0; reader.setOnClickListener(new View.OnClickListener() < int i = 0; @Override public void onClick(View v) < // TODO Auto-generated method stub i++; Handler handler = new Handler(); Runnable r = new Runnable() < @Override public void run() < i = 0; >>; if (i == 1) < //Single click handler.postDelayed(r, 250); >else if (i == 2) < if(color==1) < reader.setTextColor(0xFF000000); reader.setBackgroundColor(0xFFFFFFFF); color = 2; >else if(color==2) < reader.setTextColor(0xFFFFFFFF); reader.setBackgroundColor(0xFF000000); color=1; >i = 0; > > >); 

We have extended the OnClickListener so it can be easily applied to any view:

/** * Allows to set double click events on views. * * @param action The action to perform on click. * @param interval The maximum interval between two clicks, in milliseconds. */ class DoubleClickListener(private val action: (view: View) -> Unit, private val interval: Long = 800) : View.OnClickListener < companion object < /** The view that was clicked previously. */ private var myPreviouslyClickedView: WeakReference? = null /** * Check if the click was a second one or not. * @param view The view to check for. * * @return True if the click was a second one. */ private fun isSecondClick(view: View) = myPreviouslyClickedView?.get() == view > /** Execute the click. */ override fun onClick(view: View?) < if (view != null) < // Make sure this click is the second one if (isSecondClick(view)) < myPreviouslyClickedView?.clear() action(view) >else < // Set the previous view to this one but remove it after few moments myPreviouslyClickedView = WeakReference(view) view.postDelayed(< myPreviouslyClickedView?.clear() >, interval) > > > > 

The property myPreviouslyClickedView ensures that there can be multiple views using the listener.

Читайте также:  Json parse in javascript example

Further, we made it a bit easier to assign the listener by extending the View :

/** * Set a double click listener on a view. * * @param action The action to perform on a double click. */ fun View.setOnDoubleClickListener(action: (view: View) -> Unit) = this.setOnClickListener(DoubleClickListener(action)) 

Or, to handle custom intervals between two clicks:

/** * Set a double click listener on a view. * * @param interval The maximum interval between two clicks, in milliseconds. * @param action The action to perform on a double click. */ fun View.setTimedOnDoubleClickListener(interval: Long, action: (view: View) -> Unit) = this.setOnClickListener(DoubleClickListener(action, interval)) 

Источник

Android: How to detect double-tap?

I have a problem with implementing double tap. Well I implemented the onGestureListener and I had the gestureDetector , but I’m not sure where is the problem, here is my code:

 public class home extends TabActivity implements OnGestureListener < /** Called when the activity is first created. */ private EditText queryText; private ResultsAdapter m_adapter; private ProgressDialog pd; final Handler h = new Handler(); private TabHost mTabHost; private ArrayListsResultsArr = new ArrayList(); private String queryStr; private JSONObject searchResponse; private GestureDetector gestureScanner; final Runnable mUpdateResults = new Runnable() < public void run() < updateListUi(); >>; @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.main); Button search = (Button)findViewById(R.id.search); Button testButt = (Button)findViewById(R.id.testbutt); queryText = (EditText)findViewById(R.id.query); ListView lvr = (ListView)findViewById(R.id.search_results); //initialise the arrayAdapter this.m_adapter = new ResultsAdapter(home.this, R.layout.listrow, sResultsArr); lvr.setAdapter(this.m_adapter); lvr.setOnItemClickListener(new OnItemClickListener()< @Override public void onItemClick(AdapterViewarg0, View arg1, int arg2, long arg3) < // TODO Auto-generated method stub pd = ProgressDialog.show(home.this, null,"Loading products from server", true, false); >>); gestureScanner = new GestureDetector(this,this); gestureScanner.setOnDoubleTapListener(new OnDoubleTapListener() < public boolean onDoubleTap(MotionEvent e) < //viewA.setText("-" + "onDoubleTap" + "-"); pd = ProgressDialog.show(home.this, null,"Loading products from server", true, false); return false; >public boolean onDoubleTapEvent(MotionEvent e) < // viewA.setText("-" + "onDoubleTapEvent" + "-"); return false; >public boolean onSingleTapConfirmed(MotionEvent e) < //viewA.setText("-" + "onSingleTapConfirmed" + "-"); return false; >>); //initialise tab contents mTabHost = getTabHost(); mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Home").setContent(R.id.homepage)); mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Search Results").setContent(R.id.tab2)); mTabHost.setCurrentTab(0); //sets the respective listeners testButt.setOnClickListener(new View.OnClickListener() < public void onClick(View arg0) < if(mTabHost.getTabWidget().getVisibility()==View.GONE)< mTabHost.getTabWidget().setVisibility(View.VISIBLE); >else < mTabHost.getTabWidget().setVisibility(View.GONE); >> >); search.setOnClickListener(new View.OnClickListener() < public void onClick(View arg0) < sResultsArr.clear(); queryStr = "http://rose.mosuma.com/mobile?query=" + queryText.getText().toString(); pd = ProgressDialog.show(home.this, null,"Loading products from server", true, false); goSearch(); >>); > //updates the listUI whenever after receiving the response from the server public void updateListUi() < if(sResultsArr.size() >0) < >try < String ptypename; int count; LinearLayout ptypebar = (LinearLayout)findViewById(R.id.productCat); ptypebar.removeAllViews(); JSONArray ptypes = searchResponse.getJSONArray("ptypes"); for(int index =0;index < ptypes.length();index++)< JSONObject ptype = ptypes.getJSONObject(index); count = ptype.getInt("count"); ptypename = ptype.getString("ptypename"); //add into tab 2's UI //ImageView icon = new ImageView(this); TextView t = new TextView(home.this); t.setText(ptypename + " (" + count + ")"); ptypebar.addView(t); >> catch(JSONException e) < >//if(m_adapter.getItems() != sResultsArr) < ArrayLista = m_adapter.getItems(); a = sResultsArr; //> m_adapter.notifyDataSetChanged(); pd.dismiss(); > public void goSearch() < mTabHost.setCurrentTab(1); //separate thread for making http request and updating the arraylist Thread t = new Thread() < public void run() < searchResponse = sendSearchQuery(queryStr); try< JSONArray results = searchResponse.getJSONArray("results"); //this is stupid. i probably have to see how to make a json adapter for(int index =0;index < results.length();index++)< JSONObject product = results.getJSONObject(index); //gets the searched products from the json object URL imgUrl = new URL(product.getString("image")); String productname = product.getString("productname"); String ptypename = product.getString("ptypename"); int pid = product.getInt("pid"); int positive = product.getInt("pos"); int negative = product.getInt("neg"); int neutral = product.getInt("neu"); SearchItem item = new SearchItem(imgUrl,productname,ptypename,neutral,positive,negative,pid); sResultsArr.add(item); >> catch(JSONException e) < >catch(Exception e) < >//returns back to UI therad h.post(mUpdateResults); > >; t.start(); > //sends a request with qry as URL //and receives back a JSONobject as response public JSONObject sendSearchQuery(String qry) < HttpRequest r = new HttpRequest(); JSONObject response = r.sendHttpRequest(qry); return response; >@Override public boolean onDown(MotionEvent arg0) < return gestureScanner.onTouchEvent(arg0); >@Override public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) < // TODO Auto-generated method stub return false; >@Override public void onLongPress(MotionEvent arg0) < // TODO Auto-generated method stub >@Override public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) < // TODO Auto-generated method stub return false; >@Override public void onShowPress(MotionEvent arg0) < // TODO Auto-generated method stub >@Override public boolean onSingleTapUp(MotionEvent arg0) < // TODO Auto-generated method stub return false; >

Oh, another question, if my ListView has an onItemClickListener , can android detect between single tap or double tap for it?

Читайте также:  Питон считать одно число

Источник

Double Tap Listener Android Example

Double Tap Listener android

Create an abstract class named is DoubleClickListener which extends native View.OnClickListener. Technically nothing we are doing. Simply observe the normal click If the second click happens with delta time then we triggered onDoubleClick event. Just like below

package com.doubletaplistener import android.view.View abstract class DoubleClickListener : View.OnClickListener < private var lastClickTime: Long = 0 override fun onClick(v: View) < val clickTime = System.currentTimeMillis() if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA) < onDoubleClick(v) lastClickTime = 0 >lastClickTime = clickTime > abstract fun onDoubleClick(v: View) companion object < private const val DOUBLE_CLICK_TIME_DELTA: Long = 300 //milliseconds >>

Lets come to the implementation

For implementation double tap listener just create an android sample project. You can apply double click listener is anywhere. In this demo, I’m taking one button. On this button, I will set double click listener, for verifying this I’ll show the toast.

package com.doubletaplistener import android.os.Bundle import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // handle double tap event doubleTap.setOnClickListener(object : DoubleClickListener() < override fun onDoubleClick(v: View) < Toast.makeText(applicationContext,"Double Clicked Attempts",Toast.LENGTH_SHORT).show() >>) > >

Conclusion

In this android app Example, I show you Double Tap Listener Android Example. I hope it’s helpful for you, then help me by sharing this post with all your friends who learning android app development.

Источник

Оцените статью