본문 바로가기

Android/ToggleButton image

Android ToggleButton on/off image

안드로이드의 ToggleButton이 ON/OFF 될 때 버튼의 이미지를 변경하는 예제

프로그램이 시작되면 icon.png가 토글버튼의 배경으로 나타나고,
버튼을 눌렀을 때 버튼이 체크되면서 duke01.gif로 변경되고,
다시 눌러서 체크가 해제될 때 duke05.gif로 배경이미지가 변경된다.

사용된 이미지

사용자 삽입 이미지 사용자 삽입 이미지 사용자 삽입 이미지


main.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout android:id="@+id/LinearLayout01"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:gravity="center">
 
 <ToggleButton android:id="@+id/toggleButton01"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:textOff="Off Stage"
  android:textOn="On Stage"
  android:background="@drawable/icon"/>
 
</LinearLayout>

package com.dearpeople.android.test.togglebutton;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ToggleButton;

public class ToggleButtonActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        final ToggleButton tb = (ToggleButton)this.findViewById(R.id.toggleButton01);
       
        tb.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (tb.isChecked()) {
                 tb.setBackgroundDrawable(getResources().getDrawable(R.drawable.duke01));
                } else {
                 tb.setBackgroundDrawable(getResources().getDrawable(R.drawable.duke05));
                }
             }
        });
    }
}