안 드 로 이 드 사용자 정의 컨트롤 깊이 학습 안 드 로 이 드 생 성 랜 덤 인증 코드

지난 글 에서 사용자 정의 컨트롤 의 속성 을 소개 했다.자세 한 내용 은'안 드 로 이 드 사용자 정의 컨트롤 속성 TypedArray 및 attrs'.를 참조 하면 이 를 바탕 으로 랜 덤 인증 코드 생 성 을 실현 한다.그 안의 코드 는 사용자 정의 컨트롤 과 사용자 정의 view 그림 과 관련된다.
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.class
View 계승

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 랜 덤 인증 코드 생 성 데모
이상 은 본문의 전체 내용 이 므 로 여러분 의 학습 에 도움 이 되 기 를 바 랍 니 다.

좋은 웹페이지 즐겨찾기