Question

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.

Was it helpful?

Solution

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
                }


           }
       });

OTHER TIPS

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");
             }
         });

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top