Android

Button 을 상속하여 직접 만들기

worri-pi 2021. 7. 7. 21:16

View : 화면에 표시되는 모든 구성요소 

widget : 모양이 보이는 것 (button, textView 등)

layout : 다른 View들을 담고 있는 것

 

View를 직접 만들 수 있다. 그 중 Button(widget)을 상속하여 직접 만들어보자.

MyButton.java 파일을 새로 만들자.

 

public class MyButton extends AppCompatButton {

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

    public MyButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public void init(Context context){
        setBackgroundColor(Color.CYAN); //background 색상
        setTextColor(Color.BLUE); //text 색상
        float textSize = getResources().getDimension(R.dimen.text_size); //픽셀 단위에서 sp 단위로 바꾸기 위해 dimen 폴더에 text_size를 가져온다.
        setTextSize(textSize);
    }

    @Override
    protected void onDraw(Canvas canvas) { //어떤 상황이 되면 직접 그릴 수 있도록 Canvas 객체가 전달된다.
        super.onDraw(canvas);
        Log.d("MyButton","onDraw 호출됨"); //호출되는 시점을 보기 위해 Log를 출력했다.  
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) { //손가락이 눌렀다가 떼어질 때 호출되는 메소드이다.
        Log.d("MyButton","onTouchEvent 호출됨");

        int action = event.getAction(); //MOtionEvent에 있는 getAction 메서드를 사용해서, 손가락이 눌렸는지, 눌린 상태로 드래그되는지 또는 손가락이 뗴어졌는지 알 수 있다. int 타입으로 반환한다.
        switch (action){
            case MotionEvent.ACTION_DOWN:
                setBackgroundColor(Color.BLUE);
                setTextColor(Color.GREEN);
                break;
            case MotionEvent.ACTION_OUTSIDE:
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                setBackgroundColor(Color.CYAN);
                setTextColor(Color.BLUE);
                break;
        }
        invalidate(); //화면에 보이는 것이 유효하지 않다는 의미이다. 이걸 호출하면 reDraw 해서 onDraw를 호출한다.
        return true;
    }
}

 

안드로이드는 기본적으로 UI 구성요소는 Context 객체를 받도록 한다. Context 객체란, 예를들어 button 이라면 button 을 담고있는 주변 환경 정보이다.

첫 번째 MyButton은 소스코드에서 만들 때 호출된다.

 

AttributeSet 은 속성이다. xml 레이아웃 안에 <MyButton ...> 으로 추가할 수 있는데 <> 안에 있는 속성들이 AttributeSet에 넘어온다.

두 번째 MyButton은 레이아웃에 들어가서 inflation(버튼이 메모리에 만들어질 때) 될 때 호출된다.

 

View를 상속해서 사용할 때에는 재정의할 수 있는 함수들이 있고,어떠한 상황이 되면 자동으로 실행된다.

onMeasure()은 뷰가 스스로의 크기를 정할 때 자동으로 호출되는 메서드이다.

onDraw()는 스스로를 레이아웃에 맞게 그랠 때 자동으로 호출되는 메서드이다.

onClickEvent()는 사용자가 터치했을 때 사용하는 메서드이다.

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <org.techtown.view.MyButton //내가 만든 Button 을 호출한다.
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="확인" />
</LinearLayout>

 

 

 

728x90