Package com.gxa.custom;import android.content.context;import android.graphics.bitmap;import android.graphics.BitmapFactory;import android.graphics.Canvas;import android.graphics.Paint; import android.util.attributeset;import android.view.motionevent;import android.view.view; Import android.view.view.onclicklistener;import android.view.view.ontouchlistener;public class Customtoggle extends View implements OnClickListener,OnTouchListener{ private paint paint; private bitmap backbitmap, slidebitmap; private float slideleft,slidemax; // Slideleft:slidebitmap to the left of the Slidemax:slidebitmap, the maximum distance to slide private boolean isopen ;//Switch state private boolean isdrag;//whether sliding public Customtoggle (Context context, aTtributeset attrs) { this (context, attrs,0); } public customtoggle (Context context) { this (context,null); } Public customtoggle (context context, attributeset attrs, int defstyleattr) { super (context, attrs, defstyleattr); init (); } @Override protected void onmeasure (int widthmeasurespec, int HEIGHTMEASURESPEC) { setmeasureddimension ( Backbitmap.getwidth (), backbitmap.getheight ()); } private void init () &NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSp; paint = new paint (); Paint.setantialias (True); backbitmap = Bitmapfactory.decoderesource (Getresources (), r.drawable.togglebutton_background); slidebitmap = bitmapfactory.decoderesource (GetResources (), R.drawable.togglebutton_slide); slidemax = Backbitmap.getwidth ()-slidebitmap.getwidth (); Setonclicklistener (This), setontouchlistener (this); } @Override protected void ondraw (Canvas canvas) { canvas.drawbitmap (backBitmap, 0, 0, paint); canvas.Drawbitmap (Slidebitmap, slideleft, 0, paint); } /** * ontouch problem with return value * true Current touch events are consumed * false Current touch events are not consumed distributed activity ontouchevent Initial point of */ private float firstx; //touch private float prex;//the coordinates of the last touch @Override Public boolean ontouch (view v, motionevent event) { switch (Event.getaction ()) { case motionevent.action_down: Isdrag = false; &nbSp; firstx = event.getx (); preX = firstX; break; case MotionEvent.ACTION_MOVE: if (Math.Abs (Event.getx ()-firstx) >5) { isDrag = true; } float distance = event.getx () - prex; //sliding distance slideLeft+=distance; prex = Event.getx (); flushview (); break; case MotionEvent.ACTION_UP: if (Isdrag) { if (SLIDELEFT>SLIDEMAX/2) { isOpen = true; }else{ isopen = false; } &Nbsp; flushstatus (); } break; } return false; } private void flushstatus () { if (IsOpen) { slideLeft = slideMax; }else{ slideleft = 0; } Invalidate (); } private void flushview () { slideleft = (slideleft>=0)?slideleft:0; slideLeft = (Slideleft<=slidemax)?slideleft:slidemax; invalidate (); } @Override Public void onclick (VIEW&NBSP;V) { if (! Isdrag) { isopen = ! Isopen; flushstatus (); } }}
Custom view----mimic cool dog music slide close Close