Java 안드로이드/안드로이드
4. 기본 컨트롤 – 7. ToggleButton
언휴
2025. 1. 4. 08:02
이번에는 ToggleButton을 사용하는 간단한 실습을 합시다.

먼저 activity_main.xml 파일에 컨트롤을 배치합시다. 최상위 요소는 LinearLayout입니다. 그리고 자식으로 ToggleButton과 TextView를 배치하세요.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="com.example.ehclub.ex_togglebutton.MainActivity"
android:orientation="vertical">
<ToggleButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tb"
android:textOff="꺼짐"
android:textOn="켜짐"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:textColor="#FF0000"
android:id="@+id/tv"/>
</LinearLayout>
이제 MainActivity.java 파일을 편집합시다. MainActivity 클래스에 ToggleButton을 참조할 멤버 필드를 선언하세요.
ToggleButton tb;
onCreate 메서드에서는 먼저 findViewById 메서드를 호출하여 xml 파일에 배치한 ToggleButton을 참조합니다.
tb = (ToggleButton)findViewById(R.id.tb);
그리고 클릭 리스너를 설정합니다. 리스너에서는 xml파일에 배치한 TextView 를 참조합니다. 그리고 ToggleButton의 isChecked 메서드를 호출하여 상태에 따라 TextView의 text 속성을 설정합니다.
tb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView tv = (TextView)findViewById(R.id.tv);
if(tb.isChecked()){
tv.setText("토클 버튼 상태 : 켜짐");
}
else{
tv.setText("토클 버튼 상태 : 꺼짐");
}
}
});
다음은 MainActivity.java 파일의 내용입니다.
package com.example.ehclub.ex_togglebutton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
ToggleButton tb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tb = (ToggleButton)findViewById(R.id.tb);
tb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView tv = (TextView)findViewById(R.id.tv);
if(tb.isChecked()){
tv.setText("토클 버튼 상태 : 켜짐");
}
else{
tv.setText("토클 버튼 상태 : 꺼짐");
}
}
});
}
}
언제나휴일 추천 여행 및 산책