본문으로 바로가기

안드로이드 switch의 상태(state/option)는 두가지가 있습니다(on/off).

스위치는 유저(user)의 터치나 드래그에 의해 상태가 자동으로 변화됩니다.

하지만, 코드상에서 스위치의 상태를 바꿔주고 싶은 경우가 생긴다면, 아래와 같은 함수를 참고하시기 바랍니다.



[전제]

- 스위치 변수 정의 및 할당

(스위치 변수를 switch 라고 하겠습니다)


[방법]

상태를 변경하기 위한 함수는 총 두가지가 있습니다.


1. public void setChecked(boolean checked)

switch.setChecked(true);  // 스위치 상태 ON

switch.setChecked(false); // 스위치 상태 OFF



2. toggle()

switch.toggle();  //스위치의 현재 설정된 상태의 반대 옵션으로 변경해줍니다.


* toggle()함수는 실제 아래와 같이 구현되어있습니다.

public void toggle() {

setChecked(!isChecked());

}

때문에 스위치를 반대 상태로 변경해주고자 할 때 굉장히 편리하게 사용할 수 있는 함수입니다.

개발자가 스위치의 현재 상태를 확인(isChecked();)관리할 필요 없이 저 한 문장으로 끝나게되니까요.



두 함수는 상태를 바꾼다는 그 자체는 같지만, 

1) setChecked(true/false)함수의 경우는 직접 상태를 지정하는 것이고,

2) toggle()함수는 상태를 전환한다는 다른 맥락을 지니고 있습니다.

원하는 기능에 맞춰 알맞게 사용하시면 될 것 같습니다.







[참고]

안드로이드 Switch의 Documentation


public class Switch extends CompoundButton 

 

A Switch is a two-state toggle switch widget that can select between two options. 

The user may drag the "thumb" back and forth to choose the selected option, or simply tap to toggle as if it were a checkbox. 

The text property controls the text displayed in the label for the switch, whereas the off and on text controls the text on the thumb. 

Similarly, the textAppearance and the related setTypeface() methods control the typeface and style of label text, 

whereas the switchTextAppearance and the related setSwitchTypeface() methods control that of the thumb.

See the Toggle Buttons guide.


--> setSwitchTypeface()함수는 스위치에 나타나는 텍스트(지정한 옵션)의 스타일을 변경하는 것이다.