프로그래밍/안드로이드

안드로이드 - 스위치(Switch) 만들어서 편리하게 토글하기

가카리 2015. 8. 16. 15:16
반응형

 

스위치는 체크박스와 비슷한 역할을 하지만 조금 더 직관적으로 ON/OFF 상태를 표시할 수 있다.

 

속성

설명

text

어떤 옵션인지를 설명하는 문자열

textOn

선택했을때 표시될 문자열

textOff

선택하지 않았을 때 표시될 문자열

textStyle

문자열의 스타일, normal, bold, italic 중 하나 또는 | 연산자로 두 개 동시 지정가능

checked

초기 상태를 지정한다.

switchMinWidth

스위치의 최소 폭

switchPadding

스위치와 캡션 문자열간의 여백을 지정

thumb

스위치를 그릴 이미지를 지정

thumbTextPadding

스위치의 썸과 문자열 사이의 수평 여백을 지정

 

리스너를 등록해서 체크이벤트를 가져오고 싶으면

 

setOnCheckedChangedListener()에서 리스너를 등록하고, OnCheckedChangeListener 인터페이스를 구현하면 된다.

 

자세한건 예제소스에 있으니 참고하자.

 

activity_switch_test.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"

>

<Switch

android:text="스위치"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

/>

<Switch

android:text="Select gender"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:checked="true"

android:textOn="여자"

android:textOff="남자"

android:textSize="20dp"

android:textColor="#ff0000"

android:textStyle="bold"

android:typeface="monospace"/>

<Switch

android:text="캡션을 길게 설정할 있으며 정렬도 지정 가능하다."

android:singleLine="false"

android:gravity="bottom"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

/>

<Switch

android:id="@+id/switch1"

android:text="check event"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

/>

 

</LinearLayout>

 

 

자바 파일

SwitchTest.java

 

package com.example.ch13_switch;

 

import android.app.Activity;

import android.os.Bundle;

import android.widget.CompoundButton;

import android.widget.Toast;

import android.widget.CompoundButton.OnCheckedChangeListener;

import android.widget.Switch;

 

 

public class SwitchTest extends Activity {

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_switch_test);

        

        Switch sw = (Switch)findViewById(R.id.switch1);

        //스위치의 체크 이벤트를 위한 리스너 등록

        sw.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            

            @Override

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                // TODO Auto-generated method stub

                Toast.makeText(SwitchTest.this, "체크상태 = " + isChecked, Toast.LENGTH_SHORT).show();

                

            }

        });

    }

 

 

    

}

 

 

실행 화면

 

반응형