2

I am trying to build a custom toggle button in Android, I want it to look like radio button but function as toggle button. Can some one help me with this? any clue hints close to answer is appreciated.

David Prun
  • 8,203
  • 16
  • 60
  • 86

3 Answers3

10

You need to override the look of the toggle button via some custom xml

quick overview:

  • create png files with the look and feel of your buttons, if you like the radio buttons, grab them from ...\eclipse_android-sdk-windows\platforms\android-8\data\res\drawable-hdpi
  • in your layout xml android:background="@drawable/round_toggle" />

  • add selectors with as many states (up to 6 + default) in round_toggle.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_pressed="true" android:drawable="@drawable/roundtoggle_on_pressed" />
    <item android:state_checked="true" android:state_focused="true" 
         android:drawable="@drawable/roundtoggle_on_focused" />
    <item android:state_checked="true" android:state_focused="false"    
         android:drawable="@drawable/roundtoggle_on_normal" />       
    <item android:state_checked="false" android:state_pressed="true"
         android:drawable="@drawable/roundtoggle_off_pressed" />
    <item android:state_checked="false" android:state_focused="true"
         android:drawable="@drawable/roundtoggle_off_focused" />
    <item android:state_checked="false" android:state_focused="false"
         android:drawable="@drawable/roundtoggle_off_normal" />
    <item android:drawable="@drawable/roundtoggle_off_normal" />
    </selector>
    

full details in http://www.anddev.org/act_custom_togglebuttons-t10620.html

Noah
  • 15,080
  • 13
  • 104
  • 148
4

Why not use the RadioButton view and RadioGroup layout?

RadioButton myRadioButton = (RadioButton)findViewById(R.id.myradiobutton);
myRadioButton.setOnClickListener(new OnClickListener() {

     @Override
     public void onClick(View v) {
          // Toggle the radio button on click.
          RadioButton button = (RadioButton)v;
          button.setChecked(!button.isChecked());                   
     }
});
bporter
  • 4,467
  • 2
  • 19
  • 29
  • will try now and let you know, I cannot group them as Radio Group, I want to have individual readio buttons, that serve the purpose of toggle/check box – David Prun Aug 17 '10 at 19:01
  • If this has worked in the past it no longer works now on an HTC Hero running 2.1u1. – Hyperbole Jun 03 '11 at 04:15
0

You could try re-skinning a checkbox. The following link is a tutorial on doing so:

link

Andrew
  • 20,756
  • 32
  • 99
  • 177
  • Hello Andrew, thank you for reply, but I do not want the tick mark to be displayed. Hence I want a radio button look, if you know how to set radio button to true on click , and then set to false again on click , then please let me know. – David Prun Aug 17 '10 at 18:20