"Android" custom control implementation nine Gongge unlock

Source: Internet
Author: User

~ Reprint Please indicate source: http://blog.csdn.net/u013015161/article/details/46689011

Introduced

These two days wrote a nine Gersing control, the implementation of nine Gersing settings and unlocking. The control does not use any picture resources, and the displayed content (including dots, circles, lines, etc.) is all drawn by the brush, so it is free to reuse.
Use:

Realize

Let's start with the code.
Custom Nine Gongge controls: Locuspassview

 PackageCom.example.locusexample;ImportJava.util.ArrayList;ImportJava.util.List;ImportAndroid.content.Context;ImportAndroid.graphics.Canvas;ImportAndroid.graphics.Color;ImportAndroid.graphics.Paint;ImportAndroid.graphics.PointF;ImportAndroid.util.AttributeSet;ImportAndroid.view.MotionEvent;ImportAndroid.view.View; Public  class locuspassview extends View{    PrivatePaint Mpaint =NewPaint (Paint.anti_alias_flag);//anti-aliasing    Privatepointf[][] Mpoints =Newpointf[3][3];PrivateList<integer> pathnodes =NewArraylist<integer> ();Private floatCenterradius;//radius of each solid point    Private floatCircleradius;//Hollow Circle radius    Private floatViewwidth;Private floatViewheight;Private floatCurX =0;Private floatCurY =0;PrivateOncompletelistener Oncompletelistener =NULL; Public Locuspassview(context context, AttributeSet attrs,intDefstyle) {Super(Context, attrs, Defstyle); } Public Locuspassview(context context, AttributeSet attrs) {Super(context, attrs); } Public Locuspassview(Context context) {Super(context); }@Override     Public Boolean ontouchevent(Motionevent event) {//TODO auto-generated method stub        if(event.getaction () = = Motionevent.action_down | | event.getaction () = = Motionevent.action_move)            {CurX = Event.getx ();            CurY = Event.gety ();        Detectgetpoint (CurX, CurY); }Else if(event.getaction () = = motionevent.action_up) {if(Pathnodes.size () >=3)            {if(NULL! = Oncompletelistener) {oncompletelistener.oncomplete (pathtostring (pathnodes));        }} pathnodes.clear (); } This. Postinvalidate ();return true; }@Override    protected void OnDraw(Canvas canvas) {//TODO auto-generated method stub        Super. OnDraw (canvas); Viewwidth = This. Getmeasuredwidth (); Viewheight = This. Getmeasuredheight (); Centerradius = viewwidth/ -; Circleradius = viewwidth/6*3/5;        Drawpoints (canvas);    DrawLines (Canvas, CurX, CurY); } Public void drawpoints(Canvas canvas)        {Mpaint.setcolor (Color.Blue); Mpaint.setstyle (Paint.Style.FILL); for(inti =0; I <3; i++) { for(intj =0; J <3; J + +) {Mpoints[i][j] =NewPointF ((int) (Viewwidth/6+ Viewwidth/3* j), (int) (Viewheight/6+ Viewheight/3* i));            Canvas.drawcircle (mpoints[i][j].x, Mpoints[i][j].y, Centerradius, Mpaint);        }} mpaint.setstyle (Paint.Style.STROKE); Mpaint.setstrokewidth (Centerradius/6); for(inti =0; I < pathnodes.size (); i++) {intm = Pathnodes.get (i)/3;intn = pathnodes.get (i)%3;        Canvas.drawcircle (mpoints[m][n].x, Mpoints[m][n].y, Circleradius, Mpaint); }    } Public void DrawLines(Canvas canvas,floatCurX,floatCurY) {mpaint.setstrokewidth (Centerradius/2); PointF lastpointf =NULL; for(inti =0; I < pathnodes.size (); i++) {intm = Pathnodes.get (i)/3;intn = pathnodes.get (i)%3; PointF curpointf = Mpoints[m][n];if(NULL! = lastpointf) {canvas.drawline (lastpointf.x, Lastpointf.y, curpointf.x, Curpointf.y, Mpaint);        } lastpointf = curpointf; }if(NULL! = lastpointf) {canvas.drawline (lastpointf.x, Lastpointf.y, CurX, CurY, Mpaint); }    } Public void Detectgetpoint(floatXfloatY) { for(inti =0; I <3; i++) { for(intj =0; J <3; J + +) {if((mpoints[i][j].x-x) * (mpoints[i][j].x-x) + (mpoints[i][j].y-y) * (mpoints[i][j].y-y) < Centerradius * Centerradius *4)                 {/ * Contact enters a central point range, radius squared times 4 contacts greater ease of operation * /                    intNodenum = i *3+ J;if(!pathnodes.contains (Nodenum))                    {Pathnodes.add (nodenum); }return; }            }        }    } PublicStringpathtostring(list<integer> List) {String des =""; for(inti =0; I < list.size ();        i++) {des + = List.get (i). toString (); }returnDes }//Set completion event listener callback     Public void Setoncompletelistener(Oncompletelistener o) { This. Oncompletelistener = O; } Public  interface oncompletelistener {         Public void OnComplete(String pass); }}

The comments in the code should be more clear. The main idea is to map 9 points to integers 0 through 8 in turn. During the swipe of the finger, a list of integer types is used to save the skipped points, and the Postinvalidate method is repeatedly called OnDraw () to redraw. This includes drawing of 9 points, drawing of the circle around the point, and lines drawn between points (including the finger's current contact).

At the same time, an internal interface Oncompletelistener is written. The object in the custom view that has the interface is passed in by the Setoncompletelistener () method. When 3 or more dots are connected, the finger is lifted and the callback method OnComplete (String) is called. The string that is passed in is the integer that consists of the integral type of each selected point mapping. Externally, the string can be processed, or set, or compared.

Use and Demo

The use of the method is very simple, directly in the layout file to add the good.
Layout file: Activity_locus.xml

<linearlayout xmlns:android= " Http://schemas.android.com/apk/res/android " xmlns:tools="/HTTP/ Schemas.android.com/tools " android:layout_width=" match_parent " android: Layout_height= "match_parent"  > <com  Span class= "Hljs-preprocessor" >.example  .locusexample   android:id= "@+id/locusview"  Android:layout_width=
     
       "match_parent" 
      android:layout_height= "match_parent"  android:layout_margintop= "50DP"  android:layout_marginbottom= "50DP" /></linearlayout>  

Set the Activity:LocusSetActivity.java of the password

 PackageCom.example.locusexample;ImportCom.example.locusexample.LocusPassView.OnCompleteListener;Importandroid.app.Activity;ImportAndroid.content.Context;ImportAndroid.content.SharedPreferences;ImportAndroid.os.Bundle;ImportAndroid.widget.Toast; Public  class locussetactivity extends Activity {    @Override    protected void onCreate(Bundle savedinstancestate) {//TODO auto-generated method stub        Super. OnCreate (Savedinstancestate); This. Setcontentview (R.layout.activity_locus);FinalSharedpreferences SP = This. Getsharedpreferences ("Data", context.mode_private); Locuspassview Locusview = (Locuspassview) This. Findviewbyid (R.id.locusview); Locusview.setoncompletelistener (NewOncompletelistener () {@Override             Public void OnComplete(String Pass) {//TODO auto-generated method stubToast.maketext (locussetactivity. This,"Password is set:"+ Pass, the). Show (); Sp.edit (). Putstring ("Password", pass). commit (); Locussetactivity. This. Finish ();    }        }); }}

To unlock the Activity:LocusUnlockActivity.java

 PackageCom.example.locusexample;ImportCom.example.locusexample.LocusPassView.OnCompleteListener;Importandroid.app.Activity;ImportAndroid.content.Context;ImportAndroid.content.SharedPreferences;ImportAndroid.os.Bundle;ImportAndroid.widget.Toast; Public  class locusunlockactivity extends Activity {    @Override    protected void onCreate(Bundle savedinstancestate) {//TODO auto-generated method stub        Super. OnCreate (Savedinstancestate); This. Setcontentview (R.layout.activity_locus);FinalSharedpreferences SP = This. Getsharedpreferences ("Data", context.mode_private);FinalString Realpass = sp.getstring ("Password",NULL);if(NULL= = Realpass) {Toast.maketext ( This,"Please set the password first", the). Show (); This. Finish (); } Locuspassview Locusview = (Locuspassview) This. Findviewbyid (R.id.locusview); Locusview.setoncompletelistener (NewOncompletelistener () {@Override             Public void OnComplete(String Pass) {//TODO auto-generated method stubToast.maketext (locusunlockactivity. This,"Enter Password:"+ Pass, the). Show ();if(Pass.equals (Realpass)) {Toast.maketext (locusunlockactivity). This,"Password is correct", the). Show (); }Else{Toast.maketext (locusunlockactivity). This,"Bad password", the). Show ();    }            }        }); }}

Click to download the full demo project (shown below)

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Android" custom control implementation nine Gongge unlock

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.