Pranav
Pranav

Reputation: 4250

How to create button that behaves as toggle button?

I want functionality of toggle button in simple button.like

Button b=(Button)findViewById(R.id.x);
if(b.isChecked())
{
//do somthing
}
else
{
//do somthing
}

any one have any logic in mind ?i dont want toggle button so please help.

Upvotes: 1

Views: 1803

Answers (3)

rachit
rachit

Reputation: 1996

Its is better to use CheckBox and you can make CheckBox look like a button by changing it Background. See this link, it might help.

Upvotes: 2

Hariharan
Hariharan

Reputation: 24853

You can make use of the setTag(Object o) and getTag() attributes for button..

By default in xml set the tag as "on"(according to your need):

And then in JAVA:

        b.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                if(b.getTag().toString().trim().equals("on"))
                {
                      b.setTag("off");

                      //And your neceaasary code
                }
                else if(b.getTag().toString().trim().equals("off"))
                {
                      b.setTag("on");

                      //And your neceaasary code
                }


           }
       });

Upvotes: 4

Abdullah Shoaib
Abdullah Shoaib

Reputation: 2095

You need to apply onClickListener combined with a boolean to remember the state on your button this way:

Button button = (Button)findViewById(R.id.button);
boolean state = false;
button.setText(state?"state true":"state false");
button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 if (state)
                    state = false;
                 else
                    state = true;

                 button.setText(state?"state true":"state false");
             }
         });

Upvotes: 2

Related Questions