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
Pranav
4,2603 gold badges32 silver badges31 bronze badges
3 Answers 3
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
Hariharan
24.9k6 gold badges52 silver badges56 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Pranav
Thanks man,but i want to know why the same logic not works in boolean?
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
Abdullah Shoaib
2,0952 gold badges18 silver badges26 bronze badges
Comments
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.
Comments
default
toggle button?