Android Custom View implements methods for clicking and double-clicking Events _android

Source: Internet
Author: User

Custom View,

1. Customize a runnable thread toucheventcountthread to count the number of clicks within 500ms

2. Call the above thread in the ontouchevent in MyView

3. Customize a handler, in the Toucheventhandler processing statistics to the Click event, click, double-click, three hits, can be processed

The core code is as follows:

public class MyView extends View {...//statistics 500ms clicks toucheventcountthread mintoucheventcount = new Touchev
  Entcountthread ();

  According to the number of clicks Toucheventcountthread Statistics, perform click or double-click the event Toucheventhandler Mtoucheventhandler = new Toucheventhandler (); @Override public boolean ontouchevent (Motionevent event) {switch (event.getaction ()) {case Motionevent.actio
        N_down:if (0 = = Mintoucheventcount.touchcount)///First press, start statistics postdelayed (Mintoucheventcount, 500);
      Break 
        Case MOTIONEVENT.ACTION_UP://A Click event to have press and lift, have to lift must have pressed, so only need to action_up in the processing mintoucheventcount.touchcount++; If it is a long press operation, then the handler message cannot be touchcount to 0, requiring special handling if (Mintoucheventcount.islongclick) {Mintouchev
          Entcount.touchcount = 0;
        Mintoucheventcount.islongclick = false;
      } break;
      Case MotionEvent.ACTION_MOVE:break;
      Case MotionEvent.ACTION_CANCEL:break; Default:breaK
  Return Super.ontouchevent (event);
    The public class Toucheventcountthread implements Runnable {public int touchcount = 0;

    public Boolean islongclick = false;
      @Override public void Run () {msg = new message ();
      if (0 = touchcount) {//Long click Islongclick = true;
        else {msg.arg1 = Touchcount;
        Mtoucheventhandler.sendmessage (msg);
      Touchcount = 0; }} public class Toucheventhandler extends Handler {@Override public void Handlemessage (msg)
    {Toast.maketext (Mcontext, "touch" + Msg.arg1 + "time.", Toast.length_short). Show (); }
  }

  ......

}

The package will be as follows, so that it can be invoked elsewhere:

public interface ondoubleclicklistener{
    void OnDoubleClick (View v);
  }
  
  Private Ondoubleclicklistener Mondoubleclicklistener;

  public void Setondoubleclicklistener (Myview.ondoubleclicklistener l) {
    mondoubleclicklistener = l;
  }

  public Boolean Performdoubleclick () {
    Boolean result = false;
    if (Mondoubleclicklistener!= null) {
      Mondoubleclicklistener.ondoubleclick (this);
      result = true;
    }
    return result;
  }

  public class Toucheventhandler extends Handler {

    @Override public
    void Handlemessage (msg) {
      if (2 = = Msg.arg1)
        performdoubleclick ();
    }
  

used in activity:

Myview1.setondoubleclicklistener (New Myview.ondoubleclicklistener () {
  @Override public
  void OnDoubleClick ( View v) {
  toast.maketext (Mcontext, double click, Toast.length_short). Show ();
  }
);

All code

Myview.java

Package Com.carloz.test.myapplication.view;
Import Android.content.Context;
Import Android.content.res.TypedArray;
Import Android.graphics.Bitmap;
Import Android.graphics.BitmapFactory;
Import Android.graphics.Canvas;
Import Android.graphics.Paint;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.util.AttributeSet;
Import android.view.MotionEvent;
Import Android.view.View;

Import Android.widget.Toast;

Import COM.CARLOZ.TEST.MYAPPLICATION.R;
 /** * Created by Root on 15-11-9.
  * * public class MyView extends View {private Paint mpaint = new Paint ();
  Private Boolean Mnotdestroy = true;
  private int mcount = 0;
  Private Mythread mythread;
  Bitmap Bitmap;
  Attrs private String Mtext;
  Private Boolean Mstartchange;


  Context Mcontext;
    Public MyView {Super (context);
  Init ();
    Public MyView (context, AttributeSet attrs) {Super (context, attrs); TypedArray ta = context.obtainstyledattributes (attrs, R.styleAble.
    MyView);
    Mtext = ta.getstring (R.styleable.myview_text);
    Mstartchange = Ta.getboolean (R.styleable.myview_startchange, false);
    LOG.D ("Asdf", "mtext=" + Mtext + ", mstartchange=" + mstartchange);

    Ta.recycle ();
  Init ();
  } @Override protected void Onfinishinflate () {super.onfinishinflate (); @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {super.onmeasure (widthmeasures
  PEC, Heightmeasurespec); @Override protected void OnLayout (Boolean changed, int left, int. top, int right, int bottom) {super.onlayout (c
  Hanged, left, top, right, bottom);
    } @Override protected void OnDraw (Canvas Canvas) {Super.ondraw (Canvas);
    Mpaint.settextsize (50);
    Canvas.drawtext (Mtext + mcount++, 20f, 100f, Mpaint);
    Canvas.save ();
    Canvas.rotate (GetWidth ()/2, GetHeight ()/2);
    Canvas.drawbitmap (Bitmap, 20f, 50f, Mpaint);

    Canvas.restore (); if (null = = Mythread) {mythread = new Mythread ();
    Mythread.start ();
  @Override public boolean dispatchtouchevent (Motionevent ev) {return super.dispatchtouchevent (EV);
    } @Override protected void Onattachedtowindow () {Super.onattachedtowindow ();
  Mnotdestroy = true;
    @Override protected void Ondetachedfromwindow () {Mnotdestroy = false;
  Super.ondetachedfromwindow ();
  }//Statistics 500ms clicks toucheventcountthread mintoucheventcount = new Toucheventcountthread ();

  According to the number of clicks Toucheventcountthread Statistics, perform click or double-click the event Toucheventhandler Mtoucheventhandler = new Toucheventhandler (); @Override public boolean ontouchevent (Motionevent event) {switch (event.getaction ()) {case Motionevent.actio
        N_down:if (0 = = Mintoucheventcount.touchcount)///First press, start statistics postdelayed (Mintoucheventcount, 500);
      Break 
        Case MOTIONEVENT.ACTION_UP://A Click event to have press and lift, have to lift must have pressed, so only need to action_up in the processing mintoucheventcount.touchcount++;If it is a long press operation, then the handler message cannot be touchcount to 0, requiring special handling if (Mintoucheventcount.islongclick) {Mintoucheventcount.
          Touchcount = 0;
        Mintoucheventcount.islongclick = false;
      } break;
      Case MotionEvent.ACTION_MOVE:break;
      Case MotionEvent.ACTION_CANCEL:break;
    Default:break;
  Return Super.ontouchevent (event);
    The public class Toucheventcountthread implements Runnable {public int touchcount = 0;

    public Boolean islongclick = false;
      @Override public void Run () {msg = new message ();
      if (0 = touchcount) {//Long click Islongclick = true;
        else {msg.arg1 = Touchcount;
        Mtoucheventhandler.sendmessage (msg);
      Touchcount = 0; }} public class Toucheventhandler extends Handler {@Override public void Handlemessage (msg) {Toast.maketext (Mcontext, "touch" + Msg.arg1 + "time.", Toast.length_short). Show ();
      Class Mythread extends Thread {@Override public void run () {super.run ();
          while (Mnotdestroy) {if (Mstartchange) {postinvalidate ();
          try {thread.sleep (500);
          catch (Interruptedexception e) {e.printstacktrace ();
    '}}} ' public void init () {mcontext = GetContext ();
  Bitmap = Bitmapfactory.decoderesource (Getresources (), r.drawable.ic_launcher);
  } public void SetText (String mtext) {this.mtext = Mtext;
  } public void Setstartchange (Boolean mstartchange) {this.mstartchange = Mstartchange;
  public Boolean Getstartchange () {return this.mstartchange; }
}

Attrs.xml

<?xml version= "1.0" encoding= "Utf-8"?>
<resources>
  <declare-styleable name= "MyView" >
    <attr name= "text" format= "string"/>
    <attr name= "Startchange" format= "boolean"/>
  </ Declare-styleable>

</resources>

The Postdelayed method ultimately relies on the Handler postdelayed method to achieve the following principles

Public Final Boolean postdelayed (Runnable R, long Delaymillis)
  {return
    sendmessagedelayed getpostmessage (R), Delaymillis);
  }

  Public Final Boolean sendmessagedelayed (Message msg, long Delaymillis)
  {
    if (Delaymillis < 0) {
      Delaymillis = 0;
    }
    Return Sendmessageattime (MSG, systemclock.uptimemillis () + delaymillis);

  public boolean sendmessageattime (msg, long Uptimemillis) {
    MessageQueue queue = mqueue;
    if (queue = = null) {
      runtimeexception e = new RuntimeException (This
          + sendmessageattime () called with no Mque UE ");
      LOG.W ("Looper", E.getmessage (), e);
      return false;
    }
    return Enqueuemessage (Queue, MSG, uptimemillis); Then the time sequence is compared in the MessageQueue
  

The above is a small series for everyone to bring the Android custom view implementation Click and double-click the full contents of the event, I hope to help you, a lot of support cloud Habitat Community ~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.