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.

有帮助吗?

解决方案

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
                }


           }
       });

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top