본문 바로가기

카테고리 없음

안드로이드 스튜디오 --12. 커스텀 뷰

A> 커스텀 뷰 

--각 뷰의 생성자는 다 생성해야 한다.

 

B> onDrow 메소드

--onDraw 메소드로 그린다.

 

C> 사용

--전체 패키지 명으로 xml 에서 사용

 

D> 커스텀 속성

res/values 폴더 하위 attrs.xml에서 설정

<declare-styleable> 태그로 속성 등록

 

E> 속성값 추출

AttributeSet 을 이용해 추출

1
2
3
4
5
6
7
8
9
public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.context=context;
 
    if(attrs != null){
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);
        color=a.getColor(R.styleable.MyView_customColor, Color.RED);
    }
}
cs

 

F>onMeasure() 

-- 뷰의 크기 조정

setMeasuredDimension(width,height)

--기본 형태

1
2
3
4
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    setMeasuredDimension(500500);
}
cs

--예시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@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=0;
        int height=0;
 
        if(widthMode==MeasureSpec.AT_MOST){ //View 내부에서 지정 = wrap content
            width=700;
        }else if(widthMode==MeasureSpec.EXACTLY){ //match content
            width=widthSize;
        }
        if(heightMode==MeasureSpec.AT_MOST){
            height=250;
        }else if(heightMode==MeasureSpec.EXACTLY){
            height=heightSize;
        }
        setMeasuredDimension(width, height);
    }
 
cs

G> 커스텀 이벤트

1
2
3
4
5
6
7
8
9
10
11
12
13
public interface OnMyChangeListener {
    void onChange(int value);
}
 
public class MyPlusMinusView extends View {
    //...........
    //Observer를 등록하기 위한 객체
    ArrayList<OnMyChangeListener> listeners;
    //Observer 등록을 위한 함수
    public void setOnMyChangeListener(OnMyChangeListener listener){
        isteners.add(listener);
    }
}
cs

 

H> invlidate()

화면의 갱신