Android 사용자 정의 View 무 작위 인증 코드 작성

많은 안 드 로 이 드 입문 프로그램 원숭이 들 에 게 안 드 로 이 드 사용자 정의 View 는 비교적 두 려 울 수 있 지만 이것 은 고수 가 진급 하 는 데 필수 적 인 길이 다.모든 준 비 는 사용자 정의 View 에 시간 을 들 여 글 을 많이 쓴다.먼저 사용자 정의 View 의 절 차 를 정리 합 니 다.
1.사용자 정의 View 의 속성
2.View 의 구조 방법 에서 사용자 정의 속성 을 얻 을 수 있 습 니 다.
[3.onMesure 재 작성]
4.다시 쓰기 onDraw
나 는 3 을[]로 표 시 했 기 때문에 3 이 꼭 필요 한 것 은 아니다.물론 대부분의 경우 다시 써 야 한다.
1.View 의 속성 을 사용자 정의 합 니 다.먼저 res/values/에 있 습 니 다.  다음 attrs.xml 을 만 들 고 우리 의 속성 과 전체 스타일 을 정의 합 니 다.

<?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="CustomTitleView"> 
 <attr name="titleText" /> 
 <attr name="titleTextColor" /> 
 <attr name="titleTextSize" /> 
 </declare-styleable> 
 
</resources> 
글꼴,글꼴 색상,글꼴 크기 3 개의 속성 을 정 의 했 습 니 다.format 는 이 속성의 값 을 추출 하 는 형식 입 니 다.
모두 string,color,demension,integer,enum,reference,float,boolean,fraction,flag;잘 모 르 겠 어 요.
그리고 레이아웃 에서 사용자 정의 View 를 설명 합 니 다.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:tools="http://schemas.android.com/tools" 
 xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" > 
 
 <com.example.customview01.view.CustomTitleView 
 android:layout_width="200dp" 
 android:layout_height="100dp" 
 custom:titleText="3712" 
 custom:titleTextColor="#ff0000" 
 custom:titleTextSize="40sp" /> 
 
</RelativeLayout> 
반드시 xmlns:custom="을 도입 해 야 합 니 다.http://schemas.android.com/apk/res/com.example.customview01"우리 의 네 임 스페이스,뒤의 가방 경 로 는 프로젝트 의 package 를 말 합 니 다."
2.View 의 구조 방법 에서 사용자 정의 스타일 을 얻 을 수 있 습 니 다.

/** 
 *    
 */ 
 private String mTitleText; 
 /** 
 *       
 */ 
 private int mTitleTextColor; 
 /** 
 *       
 */ 
 private int mTitleTextSize; 
 
 /** 
 *              
 */ 
 private Rect mBound; 
 private Paint mPaint; 
 
 public CustomTitleView(Context context, AttributeSet attrs) 
 { 
 this(context, attrs, 0); 
 } 
 
 public CustomTitleView(Context context) 
 { 
 this(context, null); 
 } 
 
 /** 
 *             
 * 
 * @param context 
 * @param attrs 
 * @param defStyle 
 */ 
 public CustomTitleView(Context context, AttributeSet attrs, int defStyle) 
 { 
 super(context, attrs, defStyle); 
 /** 
 *                 
 */ 
 TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomTitleView, defStyle, 0); 
 int n = a.getIndexCount(); 
 for (int i = 0; i < n; i++) 
 { 
 int attr = a.getIndex(i); 
 switch (attr) 
 { 
 case R.styleable.CustomTitleView_titleText: 
 mTitleText = a.getString(attr); 
 break; 
 case R.styleable.CustomTitleView_titleTextColor: 
 //           
 mTitleTextColor = a.getColor(attr, Color.BLACK); 
 break; 
 case R.styleable.CustomTitleView_titleTextSize: 
 //      16sp,TypeValue    sp   px 
 mTitleTextSize = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension( 
  TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics())); 
 break; 
 
 } 
 
 } 
 a.recycle(); 
 
 /** 
 *            
 */ 
 mPaint = new Paint(); 
 mPaint.setTextSize(mTitleTextSize); 
 // mPaint.setColor(mTitleTextColor); 
 mBound = new Rect(); 
 mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound); 
 
 } 
우 리 는 세 가지 구조 방법 을 다시 썼 습 니 다.기본 레이아웃 파일 은 두 개의 매개 변수의 구조 방법 을 호출 했 기 때문에 모든 구조 가 우리 의 세 개의 매개 변수의 구 조 를 호출 하도록 하 는 것 을 기억 하 십시오.우 리 는 세 개의 매개 변수의 구조 에서 사용자 정의 속성 을 얻 었 습 니 다.
3.저 희 는 onDraw,onMesure 호출 시스템 에서 제공 하 는 것 을 다시 씁 니 다.

@Override 
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) 
 { 
 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
 } 
 
 @Override 
 protected void onDraw(Canvas canvas) 
 { 
 mPaint.setColor(Color.YELLOW); 
 canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint); 
 
 mPaint.setColor(mTitleTextColor); 
 canvas.drawText(mTitleText, getWidth() / 2 - mBound.width() / 2, getHeight() / 2 + mBound.height() / 2, mPaint); 
 } 
이때 의 효 과 는:

괜 찮 은 것 같 지 않 아 요?기본적으로 사용자 정의 View 가 이 루어 졌 습 니 다.하지만 이때 레이아웃 파일 의 너비 와 높이 를 wrap 로 쓰 면content,효 과 는 우리 가 예상 한 것 이 아 닙 니 다.

시스템 이 측정 해 준 높이 와 너 비 는 모두 MATCHPARNET,우리 가 명확 한 너비 와 높이 를 설정 할 때 시스템 이 측정 해 준 결 과 는 우리 가 설정 한 결과 입 니 다.우리 가 WRAP 로 설정 할 때.CONTENT,혹은 MATCHPARENT 시스템 이 측정 해 준 결 과 는 MATCH 입 니 다.파 렌 트 길이.
그래서 WRAP 를 설 치 했 을 때"CONTENT 때,우 리 는 스스로 측정 해 야 합 니 다.즉,onMesure 방법 을 다시 쓰 는 것 입 니 다."
다시 쓰기 전에 MeasureSpec 의 specMode 를 알 아 보 세 요.모두 세 가지 유형 입 니 다.
EXACTLY:보통 명확 한 값 이나 MATCH 를 설정 합 니 다.PARENT
AT_MOST:하위 레이아웃 이 최대 치 로 제한 되 어 있 음 을 나타 내 며,일반적으로 WARP 입 니 다.CONTENT
UNSPECIFIED:하위 레이아웃 을 원 하 는 만큼 크게 사용 하지 않 는 다 는 뜻 입 니 다.
다음은 우리 가 onMeasure 코드 를 다시 쓰 는 것 이다.

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) 
{ 
 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 
 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 
 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 
 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 
 int width; 
 int height ; 
 if (widthMode == MeasureSpec.EXACTLY) 
 { 
 width = widthSize; 
 } else 
 { 
 mPaint.setTextSize(mTitleTextSize); 
 mPaint.getTextBounds(mTitle, 0, mTitle.length(), mBounds); 
 float textWidth = mBounds.width(); 
 int desired = (int) (getPaddingLeft() + textWidth + getPaddingRight()); 
 width = desired; 
 } 
 
 if (heightMode == MeasureSpec.EXACTLY) 
 { 
 height = heightSize; 
 } else 
 { 
 mPaint.setTextSize(mTitleTextSize); 
 mPaint.getTextBounds(mTitle, 0, mTitle.length(), mBounds); 
 float textHeight = mBounds.height(); 
 int desired = (int) (getPaddingTop() + textHeight + getPaddingBottom()); 
 height = desired; 
 } 
 
 
 
 setMeasuredDimension(width, height); 
} 

현재 레이아웃 파일 을 수정 합 니 다:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:tools="http://schemas.android.com/tools" 
 xmlns:custom="http://schemas.android.com/apk/res/com.example.customview01" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" > 
 
 <com.example.customview01.view.CustomTitleView 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 custom:titleText="3712" 
 android:padding="10dp" 
 custom:titleTextColor="#ff0000" 
 android:layout_centerInParent="true" 
 custom:titleTextSize="40sp" /> 
 
</RelativeLayout> 
현재 효 과 는:

우리 의 기 대 를 완전히 복합 시 키 면 이제 우 리 는 높이,너비 에 대해 마음대로 설정 할 수 있 고 기본적으로 우리 의 수 요 를 만족 시 킬 수 있다.
물론 입 니 다.이렇게 되면 사용자 정의 View 는 TextView 에 비해 장점 이 없 지 않 습 니까?모든 사용자 정의 View 에 이 벤트 를 추가 할 것 이 라 고 생각 합 니 다.
구조 에 추가:

this.setOnClickListener(new OnClickListener() 
 { 
 
 @Override 
 public void onClick(View v) 
 { 
 mTitleText = randomText(); 
 postInvalidate(); 
 } 
 
 }); 

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(); 
 } 

다음 에 다시 실행:

우 리 는 클릭 이벤트 하 나 를 추 가 했 습 니 다.매번 무 작위 로 4 자리 의 무 작위 수 를 만 들 수 있 습 니 다.관심 있 는 것 은 onDraw 에 노 이 즈 를 추가 한 다음 인증 코드 로 바 꿀 수 있 습 니 다.느낌 이 좋 지 않 습 니까?
원본 다운로드:http://xiazai.jb51.net/201610/yuanma/AndroidCustomView(jb51.net).rar
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기