Wednesday, September 28, 2011

Android ToggleButton on/off image

android:disabledAlpha

Since: API Level
The alpha to apply to the indicator when disabled.
Must be a floating point value, such as "1.2".
This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
This corresponds to the global attribute resource symbol disabledAlpha.
Related Methods

android:textOff

Since: API Level
The text for the button when it is not checked.
Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
This corresponds to the global attribute resource symbol textOff.
Related Methods

android:textOn

Since: API Level
The text for the button when it is checked.
Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
This corresponds to the global attribute resource symbol textOn.
//
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));
                }
             }
        });
    }
}