Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

XML 스타일로 안드로이드 커스텀 버튼 만드는 방법 – 단계별 완벽 가이드

안드로이드 앱을 개발하다 보면 기본 버튼 디자인만으로는 부족할 때가 많습니다. 이번 튜토리얼에서는 XML 스타일과 Drawable 리소스를 활용해 테두리형, 그라데이션형, 원형 등 다양한 커스텀 버튼을 만드는 방법을 단계별로 알아보겠습니다.

Step 1 – 새 프로젝트 생성

Android Studio를 실행하고 File → New Project 메뉴로 이동한 후, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.

Step 2 – 레이아웃 파일 작성 (activity_main.xml)

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 세 개의 버튼이 각각 다른 배경 drawable을 참조하도록 구성되어 있습니다.

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

    <Button
        android:id="@+id/customButton"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@drawable/custom_button"
        android:text="My Custom button"/>

    <Button
        android:id="@+id/customButton2"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_below="@id/customButton"
        android:layout_marginTop="24sp"
        android:background="@drawable/custom_button2"
        android:text="My Custom button"/>

    <Button
        android:id="@+id/customButton3"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_centerInParent="true"
        android:layout_above="@id/customButton"
        android:layout_marginBottom="24sp"
        android:layout_marginTop="24sp"
        android:background="@drawable/custom_button3"
        android:text="My Custom button"/>
</RelativeLayout>

Step 3 – 첫 번째 버튼 스타일: 테두리형 (custom_button.xml)

res/drawable 폴더를 마우스 오른쪽 버튼으로 클릭한 후 New → Drawable Resource File을 선택하고, custom_button.xml이라는 이름의 파일을 생성한 뒤 아래 코드를 작성합니다.

이 스타일은 <stroke> 태그로 민트색 계열(#66F9B9)의 두꺼운 테두리를 그리고, <corners> 태그로 모서리를 둥글게 처리합니다.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <stroke android:color="#66F9B9" android:width="4dp"/>
    <corners android:radius="16sp"/>
</shape>

Step 4 – 두 번째 버튼 스타일: 그라데이션형 (custom_button2.xml)

같은 방식으로 custom_button2.xml 파일을 생성하고 아래 코드를 추가합니다.

<gradient> 태그를 사용해 시작 색상(#2AF598), 중간 색상(#ff1493), 끝 색상(colorPrimary)이 자연스럽게 이어지는 그라데이션 배경을 적용합니다. 모서리 반경을 50dp로 설정해 캡슐 형태에 가까운 버튼이 됩니다.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <gradient android:startColor="#2AF598" android:centerColor="#ff1493"
        android:endColor="@color/colorPrimary"/>
    <corners android:radius="50dp"/>
</shape>

Step 5 – 세 번째 버튼 스타일: 원형 버튼 (custom_button3.xml)

마지막으로 custom_button3.xml 파일을 생성하고 아래 코드를 작성합니다.

<solid> 태그로 와인색(#80121a) 단색 배경을 채우고, 모서리 반경을 999dp처럼 큰 값으로 지정하면 정사각형 레이아웃(200dp × 200dp)에서 완전한 원형 버튼이 만들어집니다.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <solid android:color="#80121a" />
    <corners android:radius="999dp"/>
</shape>

Step 6 – MainActivity.java 작성

src/MainActivity.java에 아래 코드를 추가합니다. 이 예제에서는 별도의 이벤트 처리 없이 레이아웃만 화면에 표시하면 됩니다.

package app.com.sample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Step 7 – AndroidManifest.xml 확인

androidManifest.xml에 아래와 같이 MainActivity가 정상적으로 등록되어 있는지 확인합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 결과를 확인해 보겠습니다. 실제 안드로이드 스마트폰을 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 상단 툴바의 Run 아이콘을 클릭하세요. 실행 옵션에서 연결된 모바일 기기를 선택하면, 기기 화면에 아래와 같이 세 가지 스타일의 커스텀 버튼이 표시됩니다.

XML 스타일로 안드로이드 커스텀 버튼 만드는 방법 – 단계별 완벽 가이드

마무리

이처럼 Drawable 리소스의 shape, stroke, gradient, solid, corners 태그만 조합해도 별도의 이미지 파일 없이 다양한 버튼 디자인을 구현할 수 있습니다. 여기에 <selector>를 함께 사용하면 눌렸을 때(pressed)나 포커스 상태별로 다른 스타일을 적용하는 것도 가능하니, 응용해 보시기 바랍니다.