1

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.

asked Dec 10, 2013 at 12:05
3
  • why to use button ? u can use checkbox out there with ur own bg Commented Dec 10, 2013 at 12:06
  • why don't you want to use a toggle button? Commented Dec 10, 2013 at 12:08
  • no requirement is only for button so plz help i want to pair buttons in horizontalscrollview and in one of the button i want togglebutton functionality ,i ussed togglebutton but there exist alignment problem. Commented Dec 10, 2013 at 12:11

3 Answers 3

4

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
 }
 }
 });
answered Dec 10, 2013 at 12:13
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man,but i want to know why the same logic not works in boolean?
2

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");
 }
 });
answered Dec 10, 2013 at 12:13

Comments

2

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.

answered Dec 10, 2013 at 12:16

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.