自定义生成验证码
ONE Goal,ONE Passion
验证码的生成是很多app注册以及登录时的必需步骤,为了防止暴力破解可以使用验证码.定义属于自己的验证码其实是件很简单的问题.
第1步:自定义继承textView的组件
/**
* 作者 : fy on 2015/12/23.
* 注释 :
*/
public class AuthCodeText extends TextView {
public AuthCodeText(Context context) {
super(context, null);
}
public AuthCodeText(Context context, AttributeSet attrs) {
super(context, attrs, 0);
}
public AuthCodeText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
this.setText(randomText());
invalidate();
break;
}
return true;
}
// 随机获得4为数字的验证码,当然可以根据自己的需要去改变验证码
private String randomText() {
Random random = new Random();
Set<Integer> set = new HashSet<Integer>();
while (set.size() < 4) {
int randomInt = random.nextInt(10);
set.add(randomInt);
}
StringBuffer sb = new StringBuffer();
for (Integer i : set) {
sb.append("" + i);
}
return sb.toString();
}
}
第2步:在需要使用的地方使用:
xml中使用:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
< <com.example.view.AuthCodeText
android:layout_width="50dp"
android:layout_height="wrap_content"
android:background="@drawable/shape"
android:text="0 0 0 0" />
</RelativeLayout>
使用的shape.xml
AndroidStudio中shape.xml写在drawable中
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="10dp" />
<solid android:color="##fff" />
</shape>
第3步:运行看效果图喽:
每次点击时会改变内容
如果项目中要使用的话自需要对一些自定义view的背景做一些改变就可以了.