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

안드로이드 Switch 위젯 커스텀 스타일 적용 방법 (썸·트랙 디자인 변경)

이 튜토리얼에서는 안드로이드 앱에서 Switch(스위치) 위젯의 기본 디자인을 변경하는 방법을 단계별로 알아봅니다. 스위치의 thumb(손잡이)track(트랙)에 커스텀 드로어블(Drawable)을 적용하여 색상과 모양을 자유롭게 바꿀 수 있습니다.

1단계 — 새 프로젝트 생성

Android Studio를 실행한 뒤, 메뉴에서 File ⇒ New Project를 선택하고 새 프로젝트 생성에 필요한 정보를 모두 입력합니다.

2단계 — 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. Switch 위젯에 android:thumb 속성과 android:track 속성으로 커스텀 드로어블을 지정하는 것이 핵심입니다.

<?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"
    android:padding="4dp"
    android:id="@+id/relativeLayout"
    tools:context=".MainActivity">
    <Switch
       android:id="@+id/switchBtn"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:textOn="ON"
       android:thumb="@drawable/customswitchselector"
       android:track="@drawable/custom_track"
       android:layout_centerInParent="true"
       android:textOff="OFF"/>
    <TextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/switchBtn"
       android:layout_marginTop="20dp"
       android:text="Switch ON and OFF"
       android:textSize="24sp"
       android:textAlignment="center"
       android:textStyle="bold"/>
</RelativeLayout>

3단계 — 썸(Thumb) 셀렉터 드로어블 만들기

res/drawable 폴더에 customswitchselector.xml이라는 드로어블 리소스 파일을 새로 만들고 아래 코드를 추가합니다. 이 파일은 스위치가 켜졌을 때(녹색 계열)꺼졌을 때(둥근 사각형) 서로 다른 배경을 보여주는 selector입니다.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <shape android:dither="true" android:shape="rectangle" android:useLevel="false" android:visible="true">
           <corners android:radius="15dp" />
           <gradient android:angle="270" android:endColor="#6600FF00" android:startColor="#66AAFF00" />
           <size android:width="37dp" android:height="37dp" />
           <stroke android:width="4dp" android:color="#0000ffff" />
        </shape>
    </item>
    <item android:state_checked="false">
        <shape android:dither="true" android:shape="rectangle" android:useLevel="false" android:visible="true">
           <corners android:radius="15dp" />
           <gradient android:angle="270" android:endColor="#ff0000" android:startColor="#ff0000" />
           <size android:width="37dp" android:height="37dp" />
           <stroke android:width="4dp" android:color="#0000ffff" />
        </shape>
    </item>
</selector>

4단계 — 트랙(Track) 드로어블 만들기

같은 방식으로 custom_track.xml 드로어블 리소스 파일을 생성하고 아래 코드를 추가합니다. 이 shape은 스위치 뒤에 위치하는 트랙의 크기(80dp × 40dp), 둥근 모서리, 반투명 배경색을 정의합니다.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    android:visible="true"
    android:dither="true"
    android:useLevel="false">
    <gradient
        android:startColor="#27170432"
        android:endColor="#27170432"
        android:angle="270"/>
    <corners
        android:radius="15dp"/>
    <size
        android:width="80dp"
        android:height="40dp" />
</shape>

5단계 — MainActivity.java 작성

src/MainActivity.java에 아래 코드를 추가합니다. setOnCheckedChangeListener()를 사용해 스위치 상태가 변경될 때마다 Toast 메시지로 ON/OFF 여부를 확인할 수 있습니다.

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    Switch aSwitch;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        aSwitch = findViewById(R.id.switchBtn);
        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Toast.makeText(MainActivity.this, "Switch On", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Switch Off", Toast.LENGTH_SHORT).show();
               }
            }
        });
    }
}

6단계 — AndroidManifest.xml 확인

androidManifest.xml에 아래와 같이 메인 액티비티가 등록되어 있는지 확인합니다.

<?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(실행) 아이콘을 클릭하세요. 실행 옵션에서 자신의 모바일 기기를 선택하면, 기본 화면에 아래와 같이 커스텀 스타일이 적용된 스위치가 표시됩니다.

안드로이드 Switch 위젯 커스텀 스타일 적용 방법 (썸·트랙 디자인 변경)

정리

Switch 위젯의 스타일을 바꾸는 핵심은 두 가지입니다. 첫째, android:thumb 속성에 상태(state_checked)에 따라 색상이 달라지는 selector 드로어블을 지정하고, 둘째, android:track 속성에 트랙의 크기와 배경을 정의한 shape 드로어블을 지정하는 것입니다. 이 방법을 응용하면 앱의 테마에 맞는 다양한 스위치 디자인을 손쉽게 구현할 수 있습니다.