안 드 로 이 드 사용자 정의 컨트롤 깊이 학습 안 드 로 이 드 생 성 랜 덤 인증 코드
12232 단어 Android사용자 정의 컨트롤인증번호
1.실현 효과 도 를 먼저 본다.
이 효과 도 보니까 괜 찮 지 않 아 요?그럼 소스 코드 를 보 세 요.
2.attr 파일
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="titleText" format="string" />
<attr name="titleTextColor" format="color" />
<attr name="titleTextSize" format="dimension" />
<declare-styleable name="AuthCodeView">
<attr name="titleText" />
<attr name="titleTextColor" />
<attr name="titleTextSize" />
</declare-styleable>
</resources>
3.레이아웃 레이아웃
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:authcodeview="http://schemas.android.com/apk/res/com.example.authcodeview"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<com.example.authcodeview.view.AuthCodeView
android:id="@+id/AuthCodeView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
authcodeview:titleText="3712"
authcodeview:titleTextColor="#00ffff"
authcodeview:titleTextSize="40sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" , " />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" " />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
</LinearLayout>
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=" " />
</LinearLayout>
4,사용자 정의 AuthCodeView.classView 계승
onMeasure(int widthMeasureSpec, int heightMeasureSpec)
onDraw(Canvas canvas)방법.코드 를 보 니 상세 한 주석 이 있 습 니 다.
package com.example.authcodeview.view;
import java.util.Random;
import com.example.authcodeview.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
public class AuthCodeView extends View
{
//
public static final int POINT_NUM = 100;
//
public static final int LINE_NUM = 2;
//
private String mTitleText;
//
private int mTitleTextColor;
//
private int mTitleTextSize;
String[] mCheckNum = new String[4];
Random random = new Random();
//
private Rect mBound;
private Paint mPaint;
public AuthCodeView(Context context, AttributeSet attrs)
{
this(context, attrs, 0);
}
public AuthCodeView(Context context)
{
this(context, null);
}
/**
*
*
* @param context
* @param attrs
* @param defStyle
*/
public AuthCodeView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
/**
*
*/
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.AuthCodeView, defStyle, 0);
// attr , AuthCodeView declare-styleable
int n = a.getIndexCount();
for (int i = 0; i < n; i++)
{
int attr = a.getIndex(i);
switch (attr)
{
// ,
case R.styleable.AuthCodeView_titleText:
mTitleText = a.getString(attr);
break;
case R.styleable.AuthCodeView_titleTextColor:
//
mTitleTextColor = a.getColor(attr, Color.BLACK);
break;
case R.styleable.AuthCodeView_titleTextSize:
// 16sp,TypeValue sp px
mTitleTextSize = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));
break;
}
}
a.recycle();
mTitleText = randomText();
/**
*
*/
mPaint = new Paint();
mPaint.setTextSize(mTitleTextSize);
mBound = new Rect();
mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound);
this.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
mTitleText = randomText();
postInvalidate();
}
});
}
//
private String randomText()
{
StringBuffer sbReturn = new StringBuffer();
for (int i = 0; i < 4; i++) {
StringBuffer sb = new StringBuffer();
int randomInt = random.nextInt(10);
mCheckNum[i] = sb.append(randomInt).toString();
sbReturn.append(randomInt);
}
return sbReturn.toString();
}
//
public String getAuthCode() {
return mTitleText;
}
// , view
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = 0;
int height = 0;
/**
*
*/
int specMode = MeasureSpec.getMode(widthMeasureSpec);
int specSize = MeasureSpec.getSize(widthMeasureSpec);
switch (specMode)
{
case MeasureSpec.EXACTLY://
width = getPaddingLeft() + getPaddingRight() + specSize;
break;
case MeasureSpec.AT_MOST:// WARP_CONTENT
width = getPaddingLeft() + getPaddingRight() + mBound.width();
break;
}
/**
*
*/
specMode = MeasureSpec.getMode(heightMeasureSpec);
specSize = MeasureSpec.getSize(heightMeasureSpec);
switch (specMode)
{
case MeasureSpec.EXACTLY://
height = getPaddingTop() + getPaddingBottom() + specSize;
break;
case MeasureSpec.AT_MOST:// WARP_CONTENT
height = getPaddingTop() + getPaddingBottom() + mBound.height();
break;
}
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas)
{
//
mPaint.setColor(Color.BLUE);
canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint);
//
mPaint.setColor(mTitleTextColor);
int [] line;
for(int i = 0; i < LINE_NUM; i ++)
{
//
mPaint.setStrokeWidth(5);
line = getLine(getMeasuredHeight(), getMeasuredWidth());
canvas.drawLine(line[0], line[1], line[2], line[3], mPaint);
}
//
int [] point;
int randomInt;
for(int i = 0; i < POINT_NUM; i ++)
{
//
randomInt = random.nextInt(5);
point = getPoint(getMeasuredHeight(), getMeasuredWidth());
canvas.drawCircle(point[0], point[1], randomInt, mPaint);
}
//
int dx = 20;
for(int i = 0; i < 4; i ++){
canvas.drawText("" + mCheckNum[i],dx, getHeight() / 2 + getPositon(mBound.height() / 2), mPaint);
dx += (getWidth() / 2 - mBound.width() / 2) + i / 5 + 20;
}
// canvas.drawText(mTitleText, getWidth() / 2 - mBound.width() / 2, getHeight() / 2 + mBound.height() / 2, mPaint);
}
// y
private int getPositon(int height) {
int tempPositoin = (int) (Math.random() * height);
if (tempPositoin < 20) {
tempPositoin += 20;
}
return tempPositoin;
}
//
public static int[] getPoint(int height, int width) {
int[] tempCheckNum = { 0, 0, 0, 0 };
tempCheckNum[0] = (int) (Math.random() * width);
tempCheckNum[1] = (int) (Math.random() * height);
return tempCheckNum;
}
//
public static int[] getLine(int height, int width) {
int[] tempCheckNum = { 0, 0, 0, 0 };
for (int i = 0; i < 4; i += 2) {
tempCheckNum[i] = (int) (Math.random() * width);
tempCheckNum[i + 1] = (int) (Math.random() * height);
}
return tempCheckNum;
}
}
5、 MainActivity AuthCodeView
package com.example.authcodeview;
import com.example.authcodeview.view.AuthCodeView;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener
{
private AuthCodeView mauthCodeView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
}
private void initUI() {
mauthCodeView = (AuthCodeView)findViewById(R.id.AuthCodeView);
findViewById(R.id.button1).setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
EditText editText = (EditText)findViewById(R.id.editText1);
String codeString = editText.getText().toString().trim();
if (codeString.equals(mauthCodeView.getAuthCode())) {
Toast.makeText(this, " !", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(this, " !", Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
}
원본 다운로드:Android 랜 덤 인증 코드 생 성 데모이상 은 본문의 전체 내용 이 므 로 여러분 의 학습 에 도움 이 되 기 를 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Bitrise에서 배포 어플리케이션 설정 테스트하기이 글은 Bitrise 광고 달력의 23일째 글입니다. 자체 또는 당사 등에서 Bitrise 구축 서비스를 사용합니다. 그나저나 며칠 전 Bitrise User Group Meetup #3에서 아래 슬라이드를 발표했...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.