Java,Android
[Android] 안드로이드 뷰가 그려지는 과정
덜지
2018. 6. 15. 11:50
안드로이드에서 제공하는 뷰를 상속받아 커스텀 뷰를 만들 때는 뷰가 그려지는 방법에 대해 이해하는 것이 중요합니다.
onMeasure() 뷰의 크기를 정함
onDraw() 뷰를 그림
onMeasure() 의 파라미터
int widthMeasureSpec, int heightMeasureSpec
이 2개의 값은 부모컨테이너에서 정한 가로, 세로의 크기이고, View.MeasureSpec 의 값입니다.
결국 이 크기 값으로 onDraw()에서 그려지게 됩니다.
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Try for a width based on our minimum
int minw = getPaddingLeft() + getPaddingRight() + getSuggestedMinimumWidth();
int w = resolveSizeAndState(minw, widthMeasureSpec, 1);
// Whatever the width ends up being, ask for a height that would let the pie
// get as big as it can
int minh = MeasureSpec.getSize(w) - (int)mTextWidth + getPaddingBottom() + getPaddingTop();
int h = resolveSizeAndState(MeasureSpec.getSize(w) - (int)mTextWidth, heightMeasureSpec, 0);
setMeasuredDimension(w, h);
}
- resolveSizeAndState() 는 final width, height 값을 만드는데 사용되는 헬퍼 메서드입니다.
- onMeasure() 은 리턴값이 없는 대신 setMeasuredDimension() 을 호출합니다. 이 메서드를 호출 안하는 경우 Exception이 발생합니다.
onDraw() 에서는
Canvas는 무엇을 그릴지를 담당하고
Paint는 어떻게 그릴지를 담당합니다.
참고
How Android Draws Views - Android docs