Android锁定EditText内容和随机生成验证码

昨天写了个小Demo,实现了随机生成验证码,和锁定EditText两个小功能,先看一下效果图:

锁定EditText在我们不需要用户编辑EditText内容的时候可以用到,实现还是很简单的,一行代码:

etLock.setEnabled(false);

随机生成验证码,主要是用了Random函数,以及将View转为Bitmap的逻辑,也没有难点,下面贴一下代码,供需要的朋友参考:

Main.java

package com.zms.textlock;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Random;

public class Main extends ActionBarActivity {
    private Button btnLock;
    private EditText etLock;
    private String numStrTmp = "";
    private String numStr = "";
    private int[] numArray = new int[4];
    private int[] colorArray = new int[6];

    private TextView tvHideA;
    private TextView tvHideB;
    private TextView tvHideC;
    private TextView tvHideD;
    private ImageView ivNumA;
    private ImageView ivNumB;
    private ImageView ivNumC;
    private ImageView ivNumD;
    private Button btnCheck;
    private TextView tvCheck;
    private EditText etCheck;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnLock = (Button) findViewById(R.id.btnLock);
        etLock = (EditText) findViewById(R.id.etLock);
        btnLock.setOnClickListener(new onClickListenerImp());

        tvHideA = (TextView) findViewById(R.id.tvHideA);
        tvHideB = (TextView) findViewById(R.id.tvHideB);
        tvHideC = (TextView) findViewById(R.id.tvHideC);
        tvHideD = (TextView) findViewById(R.id.tvHideD);
        ivNumA = (ImageView) findViewById(R.id.ivNumA);
        ivNumB = (ImageView) findViewById(R.id.ivNumB);
        ivNumC = (ImageView) findViewById(R.id.ivNumC);
        ivNumD = (ImageView) findViewById(R.id.ivNumD);

        tvCheck = (TextView) findViewById(R.id.tvCheck);
        etCheck = (EditText) findViewById(R.id.etCheck);
        btnCheck = (Button) findViewById(R.id.btnCheck);
        btnCheck.setOnClickListener(new onClickListenerImp());

        setNum();
    }

    private class onClickListenerImp implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            if (view == btnLock) {
                if (etLock.isEnabled()) {
                    etLock.setEnabled(false);
                    btnLock.setText("解锁");
                } else {
                    etLock.setEnabled(true);
                    btnLock.setText("锁定");
                }
            } else if (view == btnCheck) {
                if (etCheck.getText().toString() != null && etCheck.getText().toString().trim().length() > 0) {
                    tvCheck.setVisibility(View.VISIBLE);
                    if (numStr.equals(etCheck.getText().toString())) {
                        tvCheck.setText("输入正确");
                        tvCheck.setTextColor(Color.GREEN);
                    } else {
                        tvCheck.setText("输入错误");
                        tvCheck.setTextColor(Color.RED);
                    }
                } else {
                    setNum();
                    tvCheck.setVisibility(View.GONE);
                    //Toast.makeText(Main.this, "Please Input Verify Code", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    public void initNum() {
        numStr = "";
        numStrTmp = "";
        for (int i = 0; i < numArray.length; i++) {
            int numIntTmp = new Random().nextInt(10);
            numStrTmp = String.valueOf(numIntTmp);
            numStr = numStr + numStrTmp;
            numArray[i] = numIntTmp;
        }
    }

    public void setNum() {

        initNum();
        tvHideA.setText("" + numArray[0]);
        tvHideA.setTextColor(randomColor());
        tvHideB.setText("" + numArray[1]);
        tvHideB.setTextColor(randomColor());
        tvHideC.setText("" + numArray[2]);
        tvHideC.setTextColor(randomColor());
        tvHideD.setText("" + numArray[3]);
        tvHideD.setTextColor(randomColor());

        // Num 1
        Matrix matrixA = new Matrix();
        matrixA.reset();
        matrixA.setRotate(randomAngle());
        Bitmap bmNumA = Bitmap.createBitmap(getBitmapFromView(tvHideA, 20, 50), 0, 0, 20, 50, matrixA, true);
        ivNumA.setImageBitmap(bmNumA);
        // Num 2
        Matrix matrixB = new Matrix();
        matrixB.reset();
        matrixB.setRotate(randomAngle());
        Bitmap bmNumB = Bitmap.createBitmap(getBitmapFromView(tvHideB, 20, 50), 0, 0, 20, 50, matrixB, true);
        ivNumB.setImageBitmap(bmNumB);
        // Num 3
        Matrix matrixC = new Matrix();
        matrixC.reset();
        matrixC.setRotate(randomAngle());
        Bitmap bmNumC = Bitmap.createBitmap(getBitmapFromView(tvHideC, 20, 50), 0, 0, 20, 50, matrixC, true);
        ivNumC.setImageBitmap(bmNumC);
        // Num 4
        Matrix matrixD = new Matrix();
        matrixD.reset();
        matrixD.setRotate(randomAngle());
        Bitmap bmNumD = Bitmap.createBitmap(getBitmapFromView(tvHideD, 20, 50), 0, 0, 20, 50, matrixD, true);
        ivNumD.setImageBitmap(bmNumD);
    }

    public int randomAngle() {
        return 20 * (new Random().nextInt(5) - new Random().nextInt(3));
    }

    public int randomColor() {
        colorArray[0] = 0xFF000000; // BLACK
        colorArray[1] = 0xFFFF00FF; // MAGENTA
        colorArray[2] = 0xFFFF0000; // RED
        colorArray[3] = 0xFF00FF00; // GREEN
        colorArray[4] = 0xFF0000FF; // BLUE
        colorArray[5] = 0xFF00FFFF; // CYAN
        //colorArray[6] = 0xFFFFFF00; // YELLOW:看不清楚

        int randomColorId = new Random().nextInt(6);
        return colorArray[randomColorId];
    }

    public static Bitmap getBitmapFromView(View view, int width, int height) {
        int widthSpec = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
        int heightSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
        view.measure(widthSpec, heightSpec);
        view.layout(0, 0, width, height);
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);

        return bitmap;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

布局文件: 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".Main">

    <TextView
        android:layout_width="wrap_content"
        android:text="锁定EditText内容:"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/etLock"
            android:layout_width="200dp"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btnLock"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="锁定" />
    </LinearLayout>

    <TextView
        android:layout_marginTop="50dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="随机生成4位验证码:" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <LinearLayout
            android:id="@+id/layVerify"
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/tvHideA"
                android:layout_width="70dp"
                android:layout_height="70dp"
                android:textSize="30dp"
                android:gravity="center"
                android:visibility="gone" />

            <TextView
                android:id="@+id/tvHideB"
                android:layout_width="70dp"
                android:layout_height="70dp"
                android:textSize="30dp"
                android:gravity="center"
                android:visibility="gone" />

            <TextView
                android:id="@+id/tvHideC"
                android:layout_width="70dp"
                android:layout_height="70dp"
                android:textSize="30dp"
                android:gravity="center"
                android:visibility="gone" />

            <TextView
                android:id="@+id/tvHideD"
                android:layout_width="70dp"
                android:layout_height="70dp"
                android:textSize="30dp"
                android:gravity="center"
                android:visibility="gone" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:orientation="horizontal"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/ivNumA"
                android:layout_width="50dp"
                android:layout_height="70dp" />

            <ImageView
                android:id="@+id/ivNumB"
                android:layout_width="50dp"
                android:layout_height="70dp" />

            <ImageView
                android:id="@+id/ivNumC"
                android:layout_width="50dp"
                android:layout_height="70dp" />

            <ImageView
                android:id="@+id/ivNumD"
                android:layout_width="50dp"
                android:layout_height="70dp" />
        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/etCheck"
            android:hint="验证码"
            android:layout_width="80dp"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/tvCheck"
            android:text="结果"
            android:visibility="gone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <Button
        android:id="@+id/btnCheck"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="确定" />
</LinearLayout>

有疑问欢迎交流~

还是上传一下代码吧,是用Android Studio写的。链接:代码下载

转载请注明出处:周木水的CSDN博客 http://blog.csdn.net/zhoumushui

我的GitHub:周木水的GitHub https://github.com/zhoumushui

时间: 2024-10-06 14:20:56

Android锁定EditText内容和随机生成验证码的相关文章

bobojavascript、asp.net 实现随机生成验证码

一些网站中都有登录页面,登录时输入正确的验证码才可以,废话不多说,今天就用javascript 和异步来实现自动生成图片验证码的功能. 首先我们要插入一个一般处理程序(也就是ashx的文件,这里我给它起名为WaterMark.ashx) 这个文件所包括的引用: using System;        using System.Web;        using System.Drawing;        using System.Drawing.Drawing2D;        using

随机生成验证码及python中的事务

1.随机生成验证码 # import random # print(random.random()) #0-1的小数 # print(random.randint(1,3)) #包括1和3 # print("--",random.randrange(1,3)) #不包括1和3 #随机生成四位验证码 import random checkcode = '' for i in range(4): current = random.randrange(0,4) if current != i

Python随机生成验证码的两种方法

Python随机生成验证码的方法有很多,今天给大家列举两种,大家也可以在这个基础上进行改造,设计出适合自己的验证码方法方法一:利用range Python随机生成验证码的方法有很多,今天给大家列举两种,大家也可以在这个基础上进行改造,设计出适合自己的验证码方法 方法一: 利用range方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 # -*- coding: utf-8 -*- import random def generate_verification_c

random 模块,随机生成验证码

随机生成验证码: 此功能利用了chr 和random功能 1 res ='' 2 for i in range(6): 3 num = str(random.randint(0,9)) 4 al_num = random.randint(97,122) 5 al_num2 = random.randint(65,90) 6 alpha = chr(al_num) 7 alpha2 = chr(al_num2) 8 res += random.choice([num,alpha,alpha2])

随机生成验证码的实现+详细注释

最近的项目里需要使用到随机验证码,所以昨天认真研读了网上的许多教程,但都无非是千篇一律,不太好懂---于是乎博主就做了一回好人,对自己已经投入项目使用的一段代码进行详细的解析说明,让大家更好的理解随机验证码的生成原理!!! 这里给上我的验证码类VerifyCode.java package com.bob.verifycode; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import androi

随机生成验证码

# import random # print(random.random()) #0-1的小数 # print(random.randint(1,3)) #包括1和3 # print("--",random.randrange(1,3)) #不包括1和3 #随机生成四位验证码 import random checkcode = '' for i in range(4): current = random.randrange(0,4) if current != i: temp = c

随机生成验证码信息

package com.dyy.cache; import java.util.HashMap;      import java.util.Map;            /**      * 随机生成中文姓名,性别,Email,手机号,住址      */      public class RandomValue {          public static String base = "abcdefghijklmnopqrstuvwxyz0123456789";      

Android+Sqlite 实现内容的随机内容推送(一)

不说网络app,很多本地的app都有一些随机的内容推送,比如随机推送一些小知识,古诗,名言名画什么的,界面制作的好看一点就能看起来特别的文艺范, 最近就是看了这样的一些应用,就想自己实现一下,这种方法是自己想出来的,也不清楚那些app是怎么写出来的. 在这个里面我用了android支持的sqlite这种轻型的数据库,正好补充一下之前没怎么用过的知识点. 1.首先,需要一个数据库文件: 直接用数据库管理软件新建的sqlite会缺两个表,我也懒得自己添就用代码让android程序自己生成. 1 pa

Django随机生成验证码图片

PIL简介 什么是PIL PIL:是Python Image Library的缩写,图像处理的模块.主要的类包括Image,ImageFont,ImageDraw,ImageFilter PIL的导入 首先需要安装一下pillow包 ? 1 pip install pillow 然后就可以调用PIL里的类了 ? 1 2 3 4 from PIL import Image from PIL import ImageFont from PIL import ImageDraw from PIL im