티스토리 뷰

반응형

안드로이드의 Switch 위젯은 두 가지 옵션 중 하나를 선택할 수 있는 두 개의 상태 Toggle Switch입니다. 사용자는 두 가지 옵션 중 하나를 선택하기 위해 간단한 터치 동작이나 thumb을 앞 뒤로 드래그하여 선택할 수 있습니다.


1. Switch 주요 속성

속성명 설명
android : showText

on/off (설정/해제) Text가 보일지 안보일지를 결정하는 속성.

showText = true 설정된 모습
android : thumbTextPadding Switch Caption과 Thumb 사이의 간격
android : switchMinWidth 스위치의 너비 최소 크기
android : switchPadding Switch Caption과 스위치 사이의 간격
androiid : switchAppearance on/off Text의 Style 지정
android : textOff off 상태일 때 표시 될 Text 지정
android : textOn On 상태일 때 표시 될 Text 지정
android : textStyle Text Style(bold, italic, bolditalic)
android : thumb  사용자 드래그를 통해 on/off 설정이 가능하도록하는 thumb 모양
android : thumbTint thumb에 색상 지정
android : track track 모양 지정
android : trackTint track에 색상 지정

2. Switch 구현 예제

2.1 메인 화면 XML 레이아웃 리소스

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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">

    <Switch
        android:id="@+id/visibilitySwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:switchMinWidth="100dp"
        android:switchPadding="20dp"
        android:text="Text Visibility"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Switch
        android:id="@+id/boldSwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:switchMinWidth="100dp"
        android:switchPadding="20dp"
        android:text="Text Bold"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/visibilitySwitch" />

    <Switch
        android:id="@+id/colorSwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:switchMinWidth="100dp"
        android:switchPadding="20dp"
        android:text="Text Color"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/boldSwitch" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="Hello World"
        android:textSize="50dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/colorSwitch" />
</android.support.constraint.ConstraintLayout>

레이아웃 형태는 ConstraintLayout 아래에 Switch 3개와 TextView 한 개를 배치하였습니다. 각 Switch는 하단에 표시되는 TextView의 Style 및 Visibility에 대한 Option을 제어하도록 구현할 것입니다. 


2.2 Switch option 변경에 따른 이벤트 처리

각 Switch의 On/Off 설정 변경에 대한 이벤트 처리를 위해 각 Switch에 대한 리스너를 구현합니다.

    class visibilitySwitchListener implements CompoundButton.OnCheckedChangeListener{
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked)
                textView.setVisibility(View.INVISIBLE);
            else
                textView.setVisibility(View.VISIBLE);
        }
    }

    class boldSwitchListener implements CompoundButton.OnCheckedChangeListener{
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked)
                textView.setTypeface(null, Typeface.BOLD);
            else
                textView.setTypeface(null, Typeface.NORMAL);
        }
    }

    class colorSwitchListener implements CompoundButton.OnCheckedChangeListener{
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked)
                textView.setTextColor(Color.RED);
            else
                textView.setTextColor(Color.BLACK);
        }
    }

 

▼ CompoundButton.OnCheckedChangeListener 인터페이스를 상속받아 각 Switch에 대한 리스너를 구현합니다. 두 번째 인자로 현재 Switch가 On 인지 Off 상태인지를 체크할 수 있는 boolean 타입의 매개변수가 전달되는데 해당 변수를 통해 분기를 하여 각 Switch 설정에 따른 동작을 구현하시면 됩니다.


2.3 onCreate() 구현

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        visibilitySwitch = findViewById(R.id.visibilitySwitch);
        boldSwitch = findViewById(R.id.boldSwitch);
        colorSwitch = findViewById(R.id.colorSwitch);
        textView = findViewById(R.id.textView);

        visibilitySwitch.setOnCheckedChangeListener(new visibilitySwitchListener());
        boldSwitch.setOnCheckedChangeListener(new boldSwitchListener());
        colorSwitch.setOnCheckedChangeListener(new colorSwitchListener());
    }

▼onCreate()에서는 XML 레이아웃 리소스에 정의된 Swtich와 TextView에 대한 참조 객체를 얻어오고 앞서 구현한 리스너의 객체를 생성하여 setOnCheckedChangeListener()를 통해 리스너를 등록합니다.


3. 참조

■ Swich에 대한 안드로이드 공식 참조 문서

 

https://developer.android.com/reference/android/widget/Switch

 

■ Toggle Button에 대한 안드로이드 공식 참조 문서

 

https://developer.android.com/guide/topics/ui/controls/togglebutton.html

 

반응형