English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Building on the foundation of previous articles, let's share another one with you: Android gesture password, including source code download, don't miss it.
Source Code Download:http://xiazai.jb51.net/201610/yuanma/androidLock(jb51.net).rar
Let's take a look at the layout file of the first picture
activity_main.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" android:orientation="vertical" android:gravity="center_horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="40dip" android:textSize="24sp" android:text="gesture password" /> <Button android:id="@"+id/btn_set_lockpattern" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dip" android:text="Set gesture password" /> <Button android:id="@"+id/btn_verify_lockpattern" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dip" android:text="Verify gesture password" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dip" android:text="The password pattern is large"2"/> </LinearLayout>
See the Java code above the layout
MainActivity
package com.wujay.fund; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity implements OnClickListener { private Button mBtnSetLock; private Button mBtnVerifyLock; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setUpView(); setUpListener(); } private void setUpView() { mBtnSetLock = (Button) findViewById(R.id.btn_set_lockpattern); mBtnVerifyLock = (Button) findViewById(R.id.btn_verify_lockpattern); } private void setUpListener() { mBtnSetLock.setOnClickListener(this); mBtnVerifyLock.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_set_lockpattern: startSetLockPattern(); break; case R.id.btn_verify_lockpattern: startVerifyLockPattern(); break; default: break; } } private void startSetLockPattern() { Intent intent = new Intent(MainActivity.this, GestureEditActivity.class); startActivity(intent); } private void startVerifyLockPattern() { Intent intent = new Intent(MainActivity.this, GestureVerifyActivity.class); startActivity(intent); } }
Let's also take a look at the utility class and bean class
AppUtil
package com.wujay.fund.common; import android.content.Context; import android.view.WindowManager; public class AppUtil { public static int[] getScreenDispaly(Context context) { WindowManager windowManager = (WindowManager) context .getSystemService(Context.WINDOW_SERVICE); int width = windowManager.getDefaultDisplay().getWidth();// mobile screen width int height = windowManager.getDefaultDisplay().getHeight();// mobile screen height int result[] = { width, height }; return result; } }
Let's take a look at9Grid unit bean class
GesturePoint
package com.wujay.fund.entity; import com.wujay.fund.R; import com.wujay.fund.common.Constants; import android.widget.ImageView; public class GesturePoint { /** * status value */ private int pointState; /** representing the number represented by this Point object, from1start(Feel directly from1start)*/ private int num; private int leftX; private int rightX; private int topY; private int bottomY; private ImageView image; private int centerX; private int centerY; public GesturePoint(int leftX, int rightX, int topY, int bottomY, ImageView image, int num) { super(); this.leftX = leftX; this.rightX = rightX; this.topY = topY; this.bottomY = bottomY; this.image = image; this.centerX = (leftX + rightX) / 2; this.centerY = (topY + bottomY) / 2; this.num = num; } public int getLeftX() { return leftX; } public void setLeftX(int leftX) { this.leftX = leftX; } public int getRightX() { return rightX; } public void setRightX(int rightX) { this.rightX = rightX; } public int getTopY() { return topY; } public void setTopY(int topY) { this.topY = topY; } public int getBottomY() { return bottomY; } public void setBottomY(int bottomY) { this.bottomY = bottomY; } public ImageView getImage() { return image; } public void setImage(ImageView image) { this.image = image; } public int getCenterX() { return centerX; } public void setCenterX(int centerX) { this.centerX = centerX; } public int getCenterY() { return centerY; } public void setCenterY(int centerY) { this.centerY = centerY; } public int getPointState() { return pointState; } public void setPointState(int state) { pointState = state; switch (state) { case Constants.POINT_STATE_NORMAL: this.image.setBackgroundResource(R.drawable.gesture_node_normal); break; case Constants.POINT_STATE_SELECTED: this.image.setBackgroundResource(R.drawable.gesture_node_pressed); break; case Constants.POINT_STATE_WRONG: this.image.setBackgroundResource(R.drawable.gesture_node_wrong); break; default: break; } } public int getNum() { return num; } public void setNum(int num) { this.num = num; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + bottomY; result = prime * result + ((image == null)63; 0 : image.hashCode()); result = prime * result + leftX; result = prime * result + rightX; result = prime * result + topY; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GesturePoint other = (GesturePoint) obj; if (bottomY != other.bottomY) return false; if (image == null) { if (other.image != null) return false; } else if (!image.equals(other.image)) return false; if (leftX != other.leftX) return false; if (rightX != other.rightX) return false; if (topY != other.topY) return false; return true; } @Override public String toString() { return "Point [leftX=" + leftX + ", rightX=" + rightX + ", topY=" + topY + ", bottomY=" + bottomY + "]"; } }
Let's take a look at each position's3types
Constants
package com.wujay.fund.common; public class Constants { public static final int POINT_STATE_NORMAL = 0; // Normal state public static final int POINT_STATE_SELECTED = 1; // Press state public static final int POINT_STATE_WRONG = 2; // Error state }
Let's take a look at the interface for drawing the password
activity_gesture_edit.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#48423D" > <RelativeLayout android:id="@"+id/top_layout" android:layout_width="match_parent" android:layout_height="46dip" android:background="#000000" android:paddingLeft="20dip" android:paddingRight="20dip" android:layout_alignParentTop="true" > <TextView android:id="@"+id/text_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:gravity="center" android:text="@string/setup_gesture_code" android:textSize="20sp" android:textColor="#ffffff" /> </RelativeLayout> <LinearLayout android:id="@"+id/gesture_tip_layout" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/top_layout" android:gravity="center" android:orientation="vertical" > <TextView android:id="@"+id/text_tip" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:text="@string/set_gesture_pattern" android:textColor="#F98F12" android:layout_marginTop="10dip" /> </LinearLayout> <FrameLayout android:id="@"+id/gesture_container" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/gesture_tip_layout" android:layout_gravity="center_horizontal" android:layout_marginTop="20dip" > </FrameLayout> <TextView android:id="@"+id/text_reset" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:layout_below="@id/gesture_container" android:layout_marginTop="20dip" android:text="@string/set_gesture_pattern_reason" android:textColor="#816E6A" /> </RelativeLayout>
Let's take a look at the class for drawing the password
GestureEditActivity
package com.wujay.fund; import com.wujay.fund.R; import android.app.Activity; import android.os.Bundle; import android.text.Html; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import android.widget.TextView; import android.widget.Toast; import com.wujay.fund.widget.GestureContentView; import com.wujay.fund.widget.GestureDrawline.GestureCallBack; /** * Gesture password setting interface */ public class GestureEditActivity extends Activity implements OnClickListener { // 2prompt message for incorrect gesture password drawing private TextView mTextTip; // area for drawing gesture password private FrameLayout mGestureContainer; private GestureContentView mGestureContentView; // Reset the gesture password private TextView mTextReset; // Is it the first time to draw the password lock? private boolean mIsFirstInput = true; // Password lock generated after the first drawing is completed private String mFirstPassword = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gesture_edit); setUpViews(); setUpListeners(); } /** * Determine if the password generated after the first drawing is empty and the number of password characters is less than4 */ private boolean isInputPassValidate(String inputPassword) { if (TextUtils.isEmpty(inputPassword) || inputPassword.length() < 4) { return false; } return true; } private void setUpViews() { // Reset the gesture password mTextReset = (TextView) findViewById(R.id.text_reset); // Default not clickable mTextReset.setClickable(false); // 2prompt message for incorrect gesture password drawing mTextTip = (TextView) findViewById(R.id.text_tip); // area for drawing gesture password mGestureContainer = (FrameLayout) findViewById(R.id.gesture_container); /** * Initialize a viewGroup to display individual points GestureContentView(Context context, boolean * isVerify, String passWord, GestureCallBack callBack) */ mGestureContentView = new GestureContentView(this, false, "", new GestureCallBack() { @Override public void onGestureCodeInput(String inputCode) { // Verify the input pattern password--If the password is null or the number of password characters is less than4points if (!isInputPassValidate(inputCode)) { mTextTip.setText(Html .fromHtml("<font color='#c70c1e'>minimum connections4points, please re-enter </font>")); // Immediately clear the drawn line segments mGestureContentView.clearDrawlineState(0L); return; } if (mIsFirstInput) { // First input password--Save the first input password for comparison with the second input mFirstPassword = inputCode; // Immediately clear the drawn line segments after the first input is completed mGestureContentView.clearDrawlineState(0L); // Set the button to enable re-setting the password lock state mTextReset.setClickable(true); mTextReset .setText(getString(R.string.reset_gesture_code)); } if (inputCode.equals(mFirstPassword)) { Toast.makeText(GestureEditActivity.this, "Set successfully", Toast.LENGTH_SHORT).show(); mGestureContentView.clearDrawlineState(0L); GestureEditActivity.this.finish(); } mTextTip.setText(Html .fromHtml("<font color='#c70c1e'>Does not match the previous drawing, please redraw</font>")); // Left and right moving animation Animation shakeAnimation = AnimationUtils .loadAnimation( GestureEditActivity.this, R.anim.shake); mTextTip.startAnimation(shakeAnimation); // Keep the drawn line,1.5seconds later clear mGestureContentView.clearDrawlineState(1300L); } } mIsFirstInput = false; } @Override public void checkedSuccess() { } @Override public void checkedFail() { } }); // Set the layout where the gesture unlock is displayed mGestureContentView.setParentView(mGestureContainer); } /*****************************************************/ private void setUpListeners() { mTextReset.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.text_reset: mIsFirstInput = true; mTextTip.setText(getString(R.string.set_gesture_pattern)); break; default: break; } } }
GestureContentView
package com.wujay.fund.widget; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.wujay.fund.R; import com.wujay.fund.common.AppUtil; import com.wujay.fund.entity.GesturePoint; import com.wujay.fund.widget.GestureDrawline.GestureCallBack; /** * Gesture password container class */ public class GestureContentView extends ViewGroup { private GestureDrawline gestureDrawline; /************************************************************************ * Contains9A container for a set of ImageView, initialization * * @param context * @param isVerify * Whether it is a verification gesture password * @param passWord * User-entered password * @param callBack * Callback after gesture drawing is completed */ private int[] screenDispaly; // Divide the screen width into3Piece private int blockWidth; // 9A set of points private List<GesturePoint> list; // Environment private Context context; // Whether to verify the password private boolean isVerify; public GestureContentView(Context context, boolean isVerify, String passWord, GestureCallBack callBack) { super(context); // Get screen width screenDispaly = AppUtil.getScreenDispaly(context); // Get the screen width1/3 blockWidth = screenDispaly[0] / 3; this.list = new ArrayList<GesturePoint>(); this.context = context; this.isVerify = isVerify; // Add9icons addChild(); // Initialize a view that can draw lines gestureDrawline = new GestureDrawline(context, list, isVerify, passWord, callBack); } /** * Add9icons of the round points */ // Used to calculate2half the distance size between each circle center private int baseNum = 6; private void addChild() { for (int i = 0; i < 9; i++) { ImageView image = new ImageView(context); image.setBackgroundResource(R.drawable.gesture_node_normal); this.addView(image); invalidate(); // Which row---012 0 ,345 1, 678 2-- int row = i / 3; // Which column---012 012 , 345 012 , 678 012 int col = i % 3; // Define each attribute of the point int leftX = col * blockWidth + blockWidth / baseNum; int topY = row * blockWidth + blockWidth / baseNum; int rightX = col * blockWidth + blockWidth - blockWidth / baseNum; int bottomY = row * blockWidth + blockWidth - blockWidth / baseNum; // Build a round point object GesturePoint p = new GesturePoint(leftX, rightX, topY, bottomY, image, i + 1); // Add9a round point icon this.list.add(p); } } /** * Set the layout where the gesture unlock is displayed */ public void setParentView(ViewGroup parent) { // Get the screen width int width = screenDispaly[0]; // Set the width and height of the gesture lock--Based on the screen width LayoutParams layoutParams = new LayoutParams(width, width); // Set the width and height of the gesture lock--Based on the screen width this.setLayoutParams(layoutParams); // Also perform the same operation on the line drawing gestureDrawline.setLayoutParams(layoutParams); parent.addView(gestureDrawline); parent.addView(this); } /************************************** Operation to draw the dot position ****************************************/ @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { // Loop to get each dot position inside for (int i = 0; i < getChildCount(); i++) { // Which row int row = i / 3; // Which column int col = i % 3; // Get the corresponding dot position View v = getChildAt(i); // Perform the operation of drawing the dot position v.layout(col * blockWidth + blockWidth / baseNum, row * blockWidth + blockWidth / baseNum, col * blockWidth + blockWidth - blockWidth / baseNum, row * blockWidth + blockWidth - blockWidth / baseNum); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // Iterate over each child view and set its size for (int i = 0; i < getChildCount(); i++) { View v = getChildAt(i); v.measure(widthMeasureSpec, heightMeasureSpec); } } /** * Expose a method to the outside---Used to clear the line segments on the password lock, retaining the path delayTime for a long time * * @param delayTime */ public void clearDrawlineState(long delayTime) { gestureDrawline.clearDrawlineState(delayTime); } }
GestureDrawline
package com.wujay.fund.widget; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.wujay.fund.common.AppUtil; import com.wujay.fund.common.Constants; import com.wujay.fund.entity.GesturePoint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.PorterDuff; import android.os.Handler; import android.util.Log; import android.util.Pair; import android.view.MotionEvent; import android.view.View; import android.widget.Toast; /** * drawing the gesture password path * */ public class GestureDrawline extends View { private int mov_x;// declare the starting coordinate private int mov_y; private Map<String, GesturePoint> autoCheckPointMap;// automatically selected point private boolean isDrawEnable = true; // whether drawing is allowed /********************************************************************** * constructor */ private int[] screenDispaly; private Paint paint;// declare the pen private Canvas canvas;// canvas private Bitmap bitmap;// bitmap private List<GesturePoint> list;// a collection containing coordinates of various views private List<Pair<GesturePoint, GesturePoint>> lineList;// record the lines drawn private StringBuilder passWordSb; private boolean isVerify; private String passWord; private GestureCallBack callBack; public GestureDrawline(Context context, List<GesturePoint> list, boolean isVerify, String passWord, GestureCallBack callBack) { super(context); screenDispaly = AppUtil.getScreenDispaly(context); paint = new Paint(Paint.DITHER_FLAG);// Create a brush bitmap = Bitmap.createBitmap(screenDispaly[0], screenDispaly[0], Bitmap.Config.ARGB_8888); // Set the width and height of the bitmap canvas = new Canvas(); canvas.setBitmap(bitmap);// Draw points on the bitmap with the declared brush paint.setStyle(Style.STROKE);// Set non-filled paint.setStrokeWidth(10);// Pen width5Pixel paint.setColor(Color.rgb(245, 142, 33));// set the default line color paint.setAntiAlias(true);// Do not display jaggies this.list = list; this.lineList = new ArrayList<Pair<GesturePoint, GesturePoint>>(); initAutoCheckPointMap(); this.callBack = callBack; // Initialize password cache this.isVerify = isVerify; this.passWordSb = new StringBuilder(); this.passWord = passWord; } private void initAutoCheckPointMap() { autoCheckPointMap = new HashMap<String, GesturePoint>(); autoCheckPointMap.put("1,3", getGesturePointByNum(2)); autoCheckPointMap.put("1,7", getGesturePointByNum(4)); autoCheckPointMap.put("1,9", getGesturePointByNum(5)); autoCheckPointMap.put("2,8", getGesturePointByNum(5)); autoCheckPointMap.put("3,7", getGesturePointByNum(5)); autoCheckPointMap.put("3,9", getGesturePointByNum(6)); autoCheckPointMap.put("4,6", getGesturePointByNum(5)); autoCheckPointMap.put("7,9", getGesturePointByNum(8)); } private GesturePoint getGesturePointByNum(int num) { for (GesturePoint point : list) {}} if (point.getNum() == num) { return point; } } return null; } /********************************************************** * Draw bitmap */ @Override protected void onDraw(Canvas canvas) { canvas.drawBitmap(bitmap, 0, 0, paint); } /** * Search the collection by the point's position to find out which Point the point is included in * * @return If not found, returns null, indicating that the user's current position is between points */ private GesturePoint getPointAt(int x, int y) { for (GesturePoint point : list) {}} // First judge x int leftX = point.getLeftX(); int rightX = point.getRightX(); if (!(x >= leftX && x < rightX)) { // If it is false, jump to the next comparison continue; } int topY = point.getTopY(); int bottomY = point.getBottomY(); if (!(y >= topY && y < bottomY)) { // If it is false, jump to the next comparison continue; } // If it comes to this, it means that the position of the currently clicked point is at this position where the point is being traversed return point; } return null; } /** * clear all lines on the screen and then draw the lines in the collection */ private void clearScreenAndDrawList() { canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); for (Pair<GesturePoint, GesturePoint> pair : lineList) { // drawLine(float startX, float startY, float stopX, float stopY, // Paint paint) canvas.drawLine(pair.first.getCenterX(), pair.first.getCenterY(), pair.second.getCenterX(), pair.second.getCenterY(), paint);// Draw line } } /** * Determine if the middle point needs to be selected * * @param pointStart * @param pointEnd * @return */ private GesturePoint getBetweenCheckPoint(GesturePoint pointStart, GesturePoint pointEnd) { int startNum = pointStart.getNum(); int endNum = pointEnd.getNum(); String key = null; if (startNum < endNum) { key = startNum + " + endNum; } key = endNum + " + startNum; } return autoCheckPointMap.get(key); } /** * touch event */ private GesturePoint currentPoint; @Override public boolean onTouchEvent(MotionEvent event) { if (isDrawEnable == false) { // If the dot image shows a red negative film--It is also a secondary drawing error, which no longer allows drawing lines without clearly drawn line segments return true; } paint.setColor(Color.rgb(245, 142, 33));// set the default line color switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // get the xy coordinates of the finger position after the mouse is pressed mov_x = (int) event.getX(); mov_y = (int) event.getY(); // judge which point the current clicked position is within currentPoint = getPointAt(mov_x, mov_y); if (currentPoint != null) { currentPoint.setPointState(Constants.POINT_STATE_SELECTED); passWordSb.append(currentPoint.getNum()); } invalidate(); break; case MotionEvent.ACTION_MOVE: // clear all lines on the screen and then draw the lines in the collection--otherwise, it is not a line clearScreenAndDrawList(); // get which point the current moving position is within GesturePoint pointAt = getPointAt((int) event.getX(), (int) event.getY()); // represents that the current user's finger is before the point and point if (currentPoint == null && pointAt == null) { return true; }// represents that the user's finger moves from between points to a point if (currentPoint == null) {// firstly, judge if the current point is null // if it is empty, then assign the point where the finger moves to currentPoint currentPoint = pointAt; // set the selected state of currentPoint to true; currentPoint.setPointState(Constants.POINT_STATE_SELECTED); passWordSb.append(currentPoint.getNum()); } } if (pointAt == null || currentPoint.equals(pointAt)) { // the clicked moving area is not within the circular area, or the current clicked point is the same as the current moved point's position // then draw a line starting from the current point center and ending at the position where the finger moves to canvas.drawLine(currentPoint.getCenterX(), currentPoint.getCenterY(), event.getX(), event.getY(), paint);// Draw line } // if the current clicked point is different from the current moved point's position // then draw a line starting from the center of the previous point and ending at the position where the finger moves to canvas.drawLine(currentPoint.getCenterX(), currentPoint.getCenterY(), pointAt.getCenterX(), pointAt.getCenterY(), paint);// Draw line pointAt.setPointState(Constants.POINT_STATE_SELECTED); // Determine if the middle point needs to be selected GesturePoint betweenPoint = getBetweenCheckPoint(currentPoint, pointAt); if (betweenPoint != null && Constants.POINT_STATE_SELECTED != betweenPoint .getPointState()) { // There is a middle point and it has not been selected Pair<GesturePoint, GesturePoint> pair1 = new Pair<GesturePoint, GesturePoint>( currentPoint, betweenPoint); lineList.add(pair1); passWordSb.append(betweenPoint.getNum()); Pair<GesturePoint, GesturePoint> pair2 = new Pair<GesturePoint, GesturePoint>( betweenPoint, pointAt); lineList.add(pair2); passWordSb.append(pointAt.getNum()); // Set the middle point as selected betweenPoint.setPointState(Constants.POINT_STATE_SELECTED); // Assign the current point currentPoint = pointAt; } Pair<GesturePoint, GesturePoint> pair = new Pair<GesturePoint, GesturePoint>( currentPoint, pointAt); lineList.add(pair); passWordSb.append(pointAt.getNum()); // Assign the current point currentPoint = pointAt; } } invalidate(); break; case MotionEvent.ACTION_UP:// When the finger is lifted if (isVerify) { // Gesture password verification // Clear all lines on the screen and only draw the lines saved in the set if (passWord.equals(passWordSb.toString())) { // Represents the password gesture drawn by the user and the password passed in are the same callBack.checkedSuccess(); } // The password drawn by the user is different from the password passed in. callBack.checkedFail(); } } callBack.onGestureCodeInput(passWordSb.toString()); } break; default: break; } return true; } /************************************ * Verification error/Prompt for two inconsistent drawings */ private void drawErrorPathTip() { canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR); paint.setColor(Color.rgb(154, 7, 21));// Set default line color for (Pair<GesturePoint, GesturePoint> pair : lineList) { pair.first.setPointState(Constants.POINT_STATE_WRONG); pair.second.setPointState(Constants.POINT_STATE_WRONG); canvas.drawLine(pair.first.getCenterX(), pair.first.getCenterY(), pair.second.getCenterX(), pair.second.getCenterY(), paint);// Draw line } invalidate(); } /** * Clear the drawing state at a specified time * * @param delayTime * Delay execution time */ public void clearDrawlineState(long delayTime) { if (delayTime > 0) { // Draw red tip path isDrawEnable = false; drawErrorPathTip(); } new Handler().postDelayed(new clearStateRunnable(), delayTime); } /************************************************* * Thread for clearing drawing state */ final class clearStateRunnable implements Runnable { public void run() { // Reset passWordSb passWordSb = new StringBuilder(); // Clear the set of saved points lineList.clear(); // redraw the interface again clearScreenAndDrawList(); for (GesturePoint p : list) { p.setPointState(Constants.POINT_STATE_NORMAL); } invalidate(); isDrawEnable = true; } } public interface GestureCallBack { /** * user settings/gesture password entered */ public abstract void onGestureCodeInput(String inputCode); /** * represents that the password drawn by the user is the same as the password passed in */ public abstract void checkedSuccess(); /** * represents that the password drawn by the user is not the same as the password passed in */ public abstract void checkedFail(); } }
Next, let's look at the layout for the password lock verification
activity_gesture_verify.xml
<RelativeLayout 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" android:background="#48443c" > <LinearLayout android:id="@"+id/gesture_tip_layout" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/top_layout" android:orientation="vertical" android:paddingTop="20dip" > <TextView android:id="@"+id/text_tip" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dip" android:gravity="center_horizontal" android:textColor="#000000" android:visibility="invisible" /> </LinearLayout> <FrameLayout android:id="@"+id/gesture_container" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/gesture_tip_layout" > </FrameLayout> </RelativeLayout>
Implementation class for password verification code
GestureVerifyActivity
package com.wujay.fund; import com.wujay.fund.R; import com.wujay.fund.widget.GestureContentView; import com.wujay.fund.widget.GestureDrawline.GestureCallBack; import android.app.Activity; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.os.Bundle; import android.text.Html; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; /** * Gesture Drawing/Verification Interface */ public class GestureVerifyActivity extends Activity{ private TextView mTextTip; private FrameLayout mGestureContainer; private GestureContentView mGestureContentView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gesture_verify); setUpViews(); } private void setUpViews() { //Error prompt for verification failure mTextTip = (TextView) findViewById(R.id.text_tip); mGestureContainer = (FrameLayout) findViewById(R.id.gesture_container); // Initialize a viewGroup to display each point mGestureContentView = new GestureContentView(this, true, "12589", new GestureCallBack() { @Override public void onGestureCodeInput(String inputCode) { } @Override public void checkedSuccess() { mGestureContentView.clearDrawlineState(0L); Toast.makeText(GestureVerifyActivity.this, "Password correct", 1000).show(); GestureVerifyActivity.this.finish(); } @Override public void checkedFail() { mGestureContentView.clearDrawlineState(1300L); mTextTip.setVisibility(View.VISIBLE); mTextTip.setText(Html .fromHtml("<font color='#c70c1e'>Password error</font>")); // Left and right moving animation Animation shakeAnimation = AnimationUtils.loadAnimation(GestureVerifyActivity.this, R.anim.shake); mTextTip.startAnimation(shakeAnimation); } }); // Set the layout where the gesture unlock is displayed mGestureContentView.setParentView(mGestureContainer); } }
shake.xml
<?xml version="1.0" encoding="utf-8"?> <translate xmlns:android="http://schemas.android.com/apk/res/android" android:fromXDelta="0" android:toXDelta="10" android:duration="120" android:interpolator="@android:anim/cycle_interpolator" android:repeatMode="restart" android:repeatCount="2"/>
Recommended Articles:
Simple Version of Android Custom UI Gesture Password
Improved Version of Android Custom UI Gesture Password
That's all for this article. Hope it helps everyone's learning and also hope everyone will support the Yelling Tutorial more.
Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (When reporting, please replace # with @) for reporting violations, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.