토글 버튼은 한 번 누르면 상태가 바뀌고 다시 누르면 그 바뀐 상태에서 원래 상태로 되롤아 갑니다.
이것이 익히 생각하는 토글 버튼이고 ToggleButton 클래스로 구현이 쉽게 됩니다. 텍스트 토글 버튼이면 간답합니다. 그러나 텍스트를 이미지로 대체하면 결과는 그렇지 않다는 것을 볼 수 있습니다. 그냥 이미지가 눌러질 때 잠깐 바뀌고 다시 되돌아가는 가짜 토글일 뿐이죠.
안드로이드 기본 예제나 보통 접할 수 있는 방법으로는 이미지를 클릭하면 원하는 토글 효과를 접할 수 없습니다. 보통 클릭하는 순간 이미지가 바뀌고 손가락이 떨어지는 순간 초기 이미지로 돌아와 버립니다. 이래서는 토글이라고 할 수가 없죠. 이것은 토글 버튼이라기 보다는 딸깍 버튼이라고 부르는 것이 보다 근접한 표현이라 하겠습니다.
여기서는 위에 기술한 형태로 반응하는 버튼이 아니고 익히 생각하는 그 버튼입니다. 이미지 버튼을 클릭이나 터치하면 다른 버튼으로 바뀝니다. 손가락을 떼어도 그 변경된 상태를 그대로 유지합니다. 다시 터치를 하면 이미지는 초기 이미지로 되돌아갑니다. 이것이 진정한 토글 이미지 버튼으로서 여기 블로그를 찾은 이들에게 정확한 답변이 되겠습니다.
아래는 java 소스 변경 없이 xml만을 변경하고 추가합니다.
*************acti_main_tst_toggle.xml 파일 @layout 폴더***************************
<RelativeLayout 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"
<ToggleButton
android:background="@drawable/bttn_toggle_bg"
style="@style/OurThemeName"
android:checked="true"
android:id="@+id/tbt_tst"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ToggleButton>
</RelativeLayout>
*************themes.xml 파일 @values 폴더***************************
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Overwrite the ToggleButton style -->
<style name="Widget.Button.Toggle" parent="android:Widget">
<item name="android:background">@drawable/bttn_toggle_bg</item>
<item name="android:textOn">Add</item>
<item name="android:textOff">Del</item>
<item name="android:disabledAlpha">?android:attr/disabledAlpha</item>
</style>
<style name="OurThemeName" parent="@android:Theme.Black">
<item name="android:buttonStyleToggle">@style/Widget.Button.Toggle</item>
<item name="android:textOn"></item>
<item name="android:textOff"></item>
</style>
</resources>
*************bttn_toggle.xml 파일 @drawable폴더***************************
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_checked="true" android:drawable="@drawable/button_wine" />
<item android:state_checked="false" android:drawable="@drawable/button_wine_off" />
</selector>
*************bttn_toggle_bg.xml 파일 @drawable폴더***************************
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+android:id/background" android:drawable="@android:color/transparent" />
<item android:id="@+android:id/toggle" android:drawable="@drawable/bttn_toggle" />
</layer-list>