andbook!.pdf - Learning Android Get an anddev.org - Android-Shirt Back to index
anddev.org Header Logo
FAQ Search Top rated articles Browse Feeds anddev.org - Authors Contact Details Register Log in

Creating Custom Views - The ToggleButton

Goto page 1, 2  Next
 
       anddev.org - Android Development Community | Android Tutorials | Index -> Novice Tutorials
Author Message
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2660
Location: College Park, MD

PostPosted: Tue Dec 18, 2007 12:33 am    Post subject: Creating Custom Views - The ToggleButton Reply with quote

This Tutorial is based on the code from benderamp posted here on anddev.
Creating Custom Views - The ToggleButton


What you will learn: You will learn how to create your own custom View, a ToggleButton. Also how to use custom Views in XML and JavaCode.

Question Problems/Questions: Write it right below...

Difficulty: 1.5 of 5 Smile

What it will look like:
Unpressed State ..... and .... Pressed State


Description:
0.) The easiest way to create an customized View is to extend an existing View. In this Tutorial, we will create a Toggle Button, which extends the ordinary Button provided by the SDK.

Create a class called ToggleButton.java:
Java:
public class ToggleButton extends Button {

1.) As we want to have a ToggleButton we need to save if the Button is toggled or not.

Java:
     // ===========================================================
     // Fields
     // ===========================================================

     protected boolean isChecked = false;


2.) To use our View in Code we need a Constructor that passes the Context the ToggleButton was created in to the superclass which will handle everything that is to be done.

Java:
     // ===========================================================
     // Constructors
     // ===========================================================
     public ToggleButton(Context context) {
          super(context);
     }

3.) To make this View usable in XML-Layouts (this is called "inflate" or "inflating" we need another Constructor that passes the attributes like:
XML:
         android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="Toggle ME ..."

to the superclass which will construct (inflate) the View using the parameters specified in xml. This is the constructor that will manage what I wrote:
Java:
   public ToggleButton(Context context, AttributeSet attrs, Map params)
    {
        super(context, attrs, params);
    }


4.) We create a Getter-Method so one can check whether this ToggleButton is toggled or not:
Java:
     // ===========================================================
     // Getter & Setter
     // ===========================================================
     public boolean isChecked() {
          return this.isChecked;
     }


5.) On every click to the ToggleBotton we want to toggle is state from 'toggled <--> untoggled':
Java:
     // ===========================================================
     // Methods
     // ===========================================================

     @Override
     public boolean performClick() {
          this.isChecked = !this.isChecked;
          return super.performClick();
     }

6.) The very last thing of this class is a bit more complicated.
Java:
     /** Return an array of resource IDs of
      * the Drawable states representing the
      * current state of the view. */

     @Override
     public int[] createDrawableState() {
          int[] states;
          if (this.isChecked()) {
               // Checked
               states = Button.PRESSED_STATE_SET;
          } else {
               // Unchecked
               if (super.hasFocus()) {
                    /* Unchecked && Focus
                     * System highlights the Button */

                    states = super.createDrawableState();
               } else {
                    // Unchecked && noFocus
                    states = Button.LAST_STATE_SET;
               }
          }
          return states;
     }
}


7.) This is the way to use your Custom View in XML-Layouts. Instead of writing "<EditText ... />" you write the full package-path of the View plus its Class-Name. Of course you can use all Attributes that the superclass is capable of handling Exclamation
XML:
<org.anddev.android.customviews.ToggleButton
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="Toggle ME ..."/>


8.) Now give it a try. SetUp a primitive Activity like this:
Java:
package org.anddev.android.customviews;

import android.app.Activity;
import android.os.Bundle;

public class CustomViews extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
    }
}


And set the following as main.xml:
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

<TextView  
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Hello World, CustomViews"
    />

<org.anddev.android.customviews.ToggleButton
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="Toggle ME ..."/>

</LinearLayout>


Smile You will see the same as in the picture at the very top of this Tutorial Smile


The Full Source:
Java:
package org.anddev.android.customviews;

import java.util.Map;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;

public class ToggleButton extends Button {
     // ===========================================================
     // Fields
     // ===========================================================

     protected boolean isChecked = false;

     // ===========================================================
     // Constructors
     // ===========================================================
     public ToggleButton(Context context) {
          super(context);
     }
     
    public ToggleButton(Context context, AttributeSet attrs, Map params)
    {
        super(context, attrs, params);
    }

     // ===========================================================
     // Getter & Setter
     // ===========================================================
     public boolean isChecked() {
          return this.isChecked;
     }

     // ===========================================================
     // Methods
     // ===========================================================

     @Override
     public boolean performClick() {
          this.isChecked = !this.isChecked;
          return super.performClick();
     }

     /** Return an array of resource IDs of
      * the Drawable states representing the
      * current state of the view. */

     @Override
     public int[] createDrawableState() {
          int[] states;
          if (this.isChecked()) {
               // Checked
               states = Button.PRESSED_STATE_SET;
          } else {
               // Unchecked
               if (super.hasFocus()) {
                    /* Unchecked && Focus
                     * System highlights the Button */

                    states = super.createDrawableState();
               } else {
                    // Unchecked && noFocus
                    states = Button.LAST_STATE_SET;
               }
          }
          return states;
     }
}

Thats it Smile

Regards,
plusminus

_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
benderamp
Freshman
Freshman


Joined: 25 Nov 2007
Posts: 5

PostPosted: Fri Dec 21, 2007 7:40 am    Post subject: Reply with quote

Also a note in addition to the tutorial. Actually, android already has the class that represents toggle buttons - the CompoundButton - which already has the isCheched attribute, and also special listener class for its changes. So, it seems to be more natural to subclass from CompoundButton if one would like to implement the toggle button with custom drawing. But here is an unpleasant trap - if one would like to use standard graphics from usual Button to draw toggled/untoggled button states (like Button.LAST_STATE_SET etc) like in the tutorial, CompoundButton does not work here - if you try to change the base class in the tutorial from Button to CompoundButton, you will see that it is not drawn as on screenshots. I do not know the reason why it is so - probably Button's resource ids are not available in the CompoundButton, maybe CompoundButton overrides the onPaint() method on some unpleasant way, or maybe something else.
Back to top
View user's profile Send private message
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2660
Location: College Park, MD

PostPosted: Fri Dec 21, 2007 4:32 pm    Post subject: Reply with quote

Argh, why are they "hiding" components behind non-standard-names ^^

But one can still get the principles of creating custom views out of this tutorial Wink

Regards,
plusminus

_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
daaain
Once Poster
Once Poster


Joined: 18 Mar 2008
Posts: 1

PostPosted: Tue Mar 18, 2008 12:38 pm    Post subject: Reply with quote

hey,

i`m trying to get this work, but i get errors for createDrawableState() - it doesn`t exist anymore? i`ve tried onCreateDrawableState() and getDrawableState(), but i still couldn`t make it work, any ideas?


cheers,
dain
Back to top
View user's profile Send private message
KevGranD
Once Poster
Once Poster


Joined: 31 Mar 2008
Posts: 1
Location: France

PostPosted: Wed Apr 09, 2008 6:09 pm    Post subject: createDrawableState() remove from m5 Reply with quote

Hi,

Sorry for my english, i'm french.

i've just read that createDrawableState() had been remove for Button, somebody can show how to replace this function?
ortherwise can somebody can explain me how to change button state by code?

Regards,
KevGranD
Back to top
View user's profile Send private message
tim
Freshman
Freshman


Joined: 03 Jul 2008
Posts: 7

PostPosted: Fri Aug 15, 2008 5:31 pm    Post subject: Reply with quote

the same problem here..
how to realise toggle butttons in m5 ???
Back to top
View user's profile Send private message
myhrvod
Freshman
Freshman


Joined: 04 Aug 2008
Posts: 7

PostPosted: Sat Aug 16, 2008 4:09 pm    Post subject: Reply with quote

the same problem too.I find that this method be deleted in m5,see thisWeb Page Name
_________________
No best, Only better!
Back to top
View user's profile Send private message
JavaAndroid
Freshman
Freshman


Joined: 15 Oct 2008
Posts: 7

PostPosted: Sun Oct 19, 2008 12:45 pm    Post subject: Reply with quote

Hi All,
its not working for me....i m getting error in this method


Java:
public int[] createDrawableState() {
          int[] states;
          if (this.isChecked()) {
               // Checked
               states = Button.PRESSED_STATE_SET;
          } else {
               // Unchecked
               if (super.hasFocus()) {
                    /* Unchecked && Focus
                     * System highlights the Button */

                    states = super.createDrawableState();
               } else {
                    // Unchecked && noFocus
                    states = Button.LAST_STATE_SET;
               }
          }
          return states;
     }


Also i m getting compile time error at this line
Java:
super(context, attrs,inflateParams);


in constructor of ToggleButton class...... Can anybody figure out this problem...How to make it work??

Thanks in Advance

Thanks
JavaAndroid
Back to top
View user's profile Send private message
goelsvaibhav
Junior Developer
Junior Developer


Joined: 17 Oct 2008
Posts: 19
Location: Gurgaon, India

PostPosted: Mon Oct 20, 2008 8:00 am    Post subject: Reply with quote

Hi,

i am too getting the same errors..... Sad

Thanks
Vaibhav
Back to top
View user's profile Send private message Yahoo Messenger
rahulp
Developer
Developer


Joined: 19 Feb 2009
Posts: 29

PostPosted: Wed May 13, 2009 8:27 am    Post subject: custom view Reply with quote

hi all...
is it possible to add custom components the way we add textview... and all.
i an using eclipse.. in the layout when i click add button i can get a list of widgets.. how can i add my custom view to it..
thanks in advance

_________________
rahul phadnis
Back to top
View user's profile Send private message
sunjavaduke
Freshman
Freshman


Joined: 21 Apr 2009
Posts: 5
Location: Shanghai, China

PostPosted: Sun May 31, 2009 10:26 am    Post subject: About ToggleButton - how about iPhone-style ToggleButton? Reply with quote

Hi,

I think Android does not provide iPhone style toggle button?
Look at the picture below, when I just want to set ON|OFF for some settings, I think the iPhone style and Android style ToggleButton are both OK for me, but I have an application, I want to migrate it from iPhone SDK -> Android Platform?

Can someone give me a hint about how to do that?

P.S:
Because the iPhone style ToggleButton has a slider in it, so it supports drag&drop, Do I have to implement the TouchEvent listener?

Thanks.



togglebutton.png
 Description:
iPhone style toggle button.
 Filesize:  3.06 KB
 Viewed:  16802 Time(s)

togglebutton.png



_________________
The great thing in the world is not so much where we stand, as in what direction we are moving. - by Oliver Wendell Holmes
Back to top
View user's profile Send private message Send e-mail MSN Messenger
ioRek
Freshman
Freshman


Joined: 22 Jun 2009
Posts: 9

PostPosted: Mon Jun 22, 2009 3:15 pm    Post subject: Toggle Image Button Reply with quote

hi, I need a ToggleButton which can have an Image.

Any idea on how can I make this happen ?
Back to top
View user's profile Send private message
ohyes
Freshman
Freshman


Joined: 10 Jul 2009
Posts: 8

PostPosted: Fri Jul 10, 2009 3:12 am    Post subject: Reply with quote

JavaAndroid wrote:
Hi All,
its not working for me...

Also i m getting compile time error at this line
Java:
super(context, attrs,inflateParams);


in constructor of ToggleButton class...... Can anybody figure out this problem...How to make it work??

Thanks in Advance

Thanks
JavaAndroid


Is there any-body could fix it Sad
Please kindly help
Thank you,
-
ohyes
Back to top
View user's profile Send private message AIM Address Yahoo Messenger MSN Messenger
HBarker
Junior Developer
Junior Developer


Joined: 04 Dec 2009
Posts: 11

PostPosted: Fri Dec 04, 2009 6:11 pm    Post subject: Reply with quote

JavaAndroid wrote:

Java:
public int[] createDrawableState() {
          int[] states;
          if (this.isChecked()) {
...
     }



I believe this method was changed the following works Notice also the Button state enumerations changed as well.

Java:

     protected int[] onCreateDrawableState(int extraSpace) {
        int[] states;
        if (this.isChecked()) {
             // Checked
             states = Button.PRESSED_ENABLED_SELECTED_STATE_SET;
        } else {
             // Unchecked
             if (super.hasFocus()) {
                  /* Unchecked && Focus
                   * System highlights the Button */

                  states = super.onCreateDrawableState(extraSpace);
             } else {
                  // Unchecked && noFocus
                  states = Button.EMPTY_STATE_SET;
             }
        }
        return states;
     }


I think its important for the people out there that are just learning to learn not just the answer but how to find the answer. Taking the information I knew from the original tutorial I went to the android Developer site and searched for this function createDrawableState. Notice that it shows up in Button and In view. This is because of Inheritance Button inherits from TextView and View. But when you pull up either of those links there isn't a createDrawableState hitting search in the browser (control f) found onCreateDrawableState. Now that I had a hunch that I had the right method in eclipse I right clicked > Source > Overide Implement Methods Scrolled through them until I found my function.

JavaAndroid wrote:

Also i m getting compile time error at this line
Java:
super(context, attrs,inflateParams);

in constructor of ToggleButton class...... Can anybody figure out this problem...How to make it work??


Again this is a similar issue as the first one the methods have changed a little bit its something you'll have to get used to dealing with and Solving. If you noticed in my explanation of the other problem if you right click > Source there is alot of short cut learning goodness here. You'll notice constructors as well give a try at generating the constructors. you'll Notice that the params is no longer a Map its an int. So you'll have to modify your code somewhat to meet that expectation.
Back to top
View user's profile Send private message
HBarker
Junior Developer
Junior Developer


Joined: 04 Dec 2009
Posts: 11

PostPosted: Fri Dec 04, 2009 6:13 pm    Post subject: Reply with quote

To the Original Poster of this tutorial thanks a lot on posting this. It helped me tremendously and opened my eyes to how easy it is to create custom components.
Back to top
View user's profile Send private message
Display posts from previous:   
       anddev.org - Android Development Community | Android Tutorials | Index -> Novice Tutorials All times are GMT + 1 Hour
Goto page 1, 2  Next
Page 1 of 2

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


© 2007, Android Development Community
All rights reserved.
Powered by phpBB.