티스토리 뷰

반응형

안드로이드 프로그래밍을 하다보면 사용자 측에서 디자인 관련 다양한 요구사항이 들어옵니다. 버튼 모서리를 둥글게 해주세요! 아니 완전 원으로 해주세요! 버튼에 이미지를 넣어주세요! 그림자도 필요해요!  정사각형으로 해주세요! 등등. 디자이너가 아니라서 포토샵으로 이미지를 만드는 작업은 그렇다 치고, 최소한 코드로 예쁜 버튼을 만들기 위해 노력을 해야합니다. 그것이 일환으로 이번에는 정사각형 버튼을 만들어 보겠습니다. 처음에는 xml에서 그냥 "android:layout_width = android:layout_height" 라고 코딩하면 될까 싶었지만 역시나 안되더군요. 어쩔 수 없이 Button 위젯을 상속해야 했습니다.

 

안드로이드 프로그래밍 정사각형 버튼(Button) 만들기


안드로이드 프로그래밍에서 정사각형 버튼을 만들기 위해서는 우선 Button 위젯을 상속받아 또 다른 클래스(SquareButton)을 만들어야 합니다. 그리고 나서 프로그램의 레이아웃을 담당하는 activity_main.xml 파일에서 그 버튼을 사용하면 됩니다. 그럼 상속을 사용해서 SquareButton 클래스를 만들어 보겠습니다.

 

SquareButton.java

public class SquareButton extends Button {

	public SquareButton(Context context) {
		super(context);
	}

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

	public SquareButton(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

		int width = MeasureSpec.getSize(widthMeasureSpec);
		int height = MeasureSpec.getSize(heightMeasureSpec);

		width = Math.min(width, height);
		height = width;

		setMeasuredDimension(width, height);
	}
}

클래스 파일을 하나 만들기 위해서는 프로젝트명 위에 오른쪽 마우스 클릭을 합니다. 그럼 팝업메뉴가 뜨는데 거기서 New - Class 를 선택합니다. 그럼 New Java Class라는 대화상자가 나오는데 간단하게 Name에 SquareButton을, Superclass에는 Button을 선택하고 Finish버튼을 누릅니다. 그럼 프로젝트 패키지에 자바파일이 하나 생성되는데 여기에 위 코드를 입렵하면 됩니다. 생성자 같은 경우는 오류가 나는 부분에 마우스 커서를 사용해서 자동으로 만들 수 있습니다. 여기서 핵심은 OnMeasure() 이벤트 함수(콜백 메서드)입니다. 이 메서드는 화면에 뷰가 출력되기 전 넓이와 높이를 변경할 수 있는 기회를 줍니다. 소스코드는 매우 단순하고 함수의 이름만 봐도 무슨 역할을 하는지 다 알 수 있기 때문에 설명은 생략하겠습니다. 그렇게 Button의 서브클래스(SquareButton)을 만들었으면 레이아웃(activity_main)에서 사용을 해야합니다.

 

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.helloworld.MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <com.example.helloworld.SquareButton
            android:layout_width="0px"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher"
            android:text="one" />

        <com.example.helloworld.SquareButton
            android:layout_width="0px"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher"
            android:text="two" />

        <com.example.helloworld.SquareButton
            android:layout_width="0px"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher"
            android:text="three" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <com.example.helloworld.SquareButton
            android:layout_width="0px"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher"
            android:text="four" />

        <com.example.helloworld.SquareButton
            android:layout_width="0px"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher"
            android:text="five" />

        <com.example.helloworld.SquareButton
            android:layout_width="0px"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher"
            android:text="six" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <com.example.helloworld.SquareButton
            android:layout_width="0px"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher"
            android:text="seven" />

        <com.example.helloworld.SquareButton
            android:layout_width="0px"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher"
            android:text="eight" />

        <com.example.helloworld.SquareButton
            android:layout_width="0px"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher"
            android:text="nine" />
    </LinearLayout>

</LinearLayout>

이 레이아웃에서는 정사각형 버튼을 9개 만들고 있습니다. 가로, 세로 3x3으로 조금만 수정한다면 전화를 걸거나 숫자를 다루는 프로젝트에 활용해도 될 것 같습니다. 안드로이드 프로그래밍 초보도 쉽게 분석할 수 있는 코드인데 한 가지만 주의하면 됩니다. 프로젝트에서 직접 생성한 클래스(위젯)는 XML 레이아웃 파일에서 사용할 때 풀 패키지명(com.example.helloworld.SquareButton)을 다 입력해 줘야한다는 것입니다. 그것만 주의하면 됩니다.

 

SquareButton.java파일과 activity_main파일을 이렇게 입력하고 실행을 하면, 위 사진처럼 정사각형 버튼 9개가 제대로 출력되는 것을 볼 수 있습니다. 핵심은 Button 클래스(위젯)을 상속받아 OnMeasure() 메서드를 오버라이딩(재정의)을 해야 한다는 것입니다. 그럼 행복한 코딩하세요!

 

 

반응형
댓글