안 드 로 이 드 개발 아 트 탐색 노트

전 재 를 환영 합 니 다.http://blog.csdn.net/l664675249/article/details/50787973
사용자 정의 뷰
이 사용자 정의 View 는 매우 간단 합 니 다. 원 을 그 려 서 원형 효 과 를 실현 하 는 사용자 정의 View 입 니 다.
먼저 규범 에 맞지 않 는 사용자 정의 View 가 어떻게 하 는 지 봅 시다.
public class CircleView extends View {

    private int mColor = Color.RED;
    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public CircleView(Context context) {
        super(context);
        init();
    }

    public CircleView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mPaint.setColor(mColor);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int width = getWidth();
        int height = getHeight();
        int radius = Math.min(width, height) / 2;
        canvas.drawCircle(width / 2, height / 2, radius, mPaint);
    }
}

대응 하 는 xml
<com.ryg.chapter_4.ui.CircleView  android:id="@+id/circleView1" android:layout_width="match_parent" android:layout_height="100dp" android:layout_margin="20dp" android:background="#000000" />

이렇게 하면 원 을 그 릴 수 있 지만 이것 은 규범 화 된 사용자 정의 View 가 아니 라 다음 과 같은 문제 가 존재 합 니 다.
  • android: padding 속성 은 사용 할 수 없습니다
  • wrap 사용content 는 match 를 사용 하 는 것 과 같 습 니 다.partent

  • 사용자 정의 뷰
    이상 의 문 제 를 해결 하기 위해 서 는 View 의 onMeasure 와 onDraw 방법 을 다시 써 야 합 니 다.
    전체 코드 는 다음 과 같 습 니 다:
    public class CircleView extends View {
    
        private int mColor = Color.RED;
        private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    
        public CircleView(Context context) {
            super(context);
            init();
        }
    
        public CircleView(Context context, AttributeSet attrs) {
            this(context, attrs, 0);
        }
    
        public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView);
            mColor = a.getColor(R.styleable.CircleView_circle_color, Color.RED);
            a.recycle();
            init();
        }
    
        private void init() {
            mPaint.setColor(mColor);
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
            int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
            int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
            int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
            if (widthSpecMode == MeasureSpec.AT_MOST
                    && heightSpecMode == MeasureSpec.AT_MOST) {
                setMeasuredDimension(200, 200);
            } else if (widthSpecMode == MeasureSpec.AT_MOST) {
                setMeasuredDimension(200, heightSpecSize);
            } else if (heightSpecMode == MeasureSpec.AT_MOST) {
                setMeasuredDimension(widthSpecSize, 200);
            }
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            final int paddingLeft = getPaddingLeft();
            final int paddingRight = getPaddingRight();
            final int paddingTop = getPaddingTop();
            final int paddingBottom = getPaddingBottom();
            int width = getWidth() - paddingLeft - paddingRight;
            int height = getHeight() - paddingTop - paddingBottom;
            int radius = Math.min(width, height) / 2;
            canvas.drawCircle(paddingLeft + width / 2, paddingTop + height / 2,
                    radius, mPaint);
        }
    }

    사용자 정의 속성 추가
  • values 폴 더 에 attrs. xml
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <declare-styleable name="CircleView">
            <attr name="circle_color" format="color" />
        </declare-styleable>
    </resources>
    사용자 정의 속성 집합 CircleView 를 추가 합 니 다. 이 속성 집합 에 서 는 color 의 속성 circle 형식 만 정의 합 니 다.color。
  • View 의 구조 함수 에서 사용자 정의 속성 분석
     public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView);
            mColor = a.getColor(R.styleable.CircleView_circle_color, Color.RED);
            a.recycle();
            init();
        }
  • 레이아웃 파일 에 사용자 정의 속성
       <com.ryg.chapter_4.ui.CircleView  android:id="@+id/circleView1" android:layout_width="wrap_content" android:layout_height="100dp" android:layout_margin="20dp" android:background="#000000" android:padding="20dp" app:circle_color="@color/light_green" />
    을 사용 하여 사용자 정의 속성 을 사용 할 때 schemas 성명: xmlns: app = "http://schemas.android.com/apk/res-auto", 사용 시 일반 속성 과 유사, app: circlecolor=”@color/light_green” 。

  • 사용자 정의 뷰 주의사항
  • 사용자 정의 View 에서 margin 속성 을 사용 할 수 있 습 니 다. 부모 용기 에 의 해 제어 되 기 때 문 입 니 다
  • View 또는 View Group 을 직접 계승 하려 면 wrapcontent
  • View 는 onDraw 방법 에서 padding 을 처리 하고 ViewGroup 은 onMeasure 와 onLayout 에서 padding 과 margin
  • 을 처리 해 야 합 니 다.
  • View 의 post 방법 은 handler
  • 를 대체 할 수 있다.
  • View 의 onDetached FromWindow 에서 애니메이션 을 중단 하고 메모리 유출 방지
  • 미끄럼 내장 상황 이 있 을 때 미끄럼 충돌 처리 에 주의 하 십시오
  • 위 에 언급 된 몇 가지 유형 과 방법 에 대한 상세 한 설명 은 참고 하 시기 바 랍 니 다.http://blog.csdn.net/l664675249/article/details/50774617

  • 예 쁜 뷰 를 사용자 정의 하 는 것 은 쉽 지 않 습 니 다. 많이 읽 고 많이 쓰 고 많이 측정 해 야 더 잘 파악 할 수 있 습 니 다.스스로 바퀴 를 만 들 고 성숙 한 바퀴 를 비교 해 차이 와 부족 을 찾는다.
    전 재 를 환영 합 니 다.http://blog.csdn.net/l664675249/article/details/50787973

    좋은 웹페이지 즐겨찾기