Reputation: 1736
I am trying to change the default On and Off text on the toggle button in Android. I am aware of how to do this in xml. My query is how to attain this programatically in code.
Could anyone please advise? Much thanks.
Upvotes: 2
Views: 3986
Reputation: 6104
Use ToggleButton.setTextOn(String)
and ToggleButton.setTextOff(String)
Upvotes: 3
Reputation: 6037
you can set in toggle button on/off in xml like below
// xml code for toggle button
<ToggleButton
android:id="@+id/toggBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:gravity="center"
android:textOn="On" //when your button on by clicking "On" text will be displayed
android:textOff="Off" /> //When you off the toggle button "Off" text will be displayed
in java code.
ToggleButton toggleButton=(ToggleButton)findViewById(R.id.toggBtn);
toggleButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
if(toggleButton.getText().toString().equals("on")){
////do when toggle button is on
}else if(toggleButton.getText().toString().equals("off")){
// do when toggle button is off
}
}
});
Upvotes: 1
Reputation: 3081
You can try something like this:
ToggleButton btn = new ToggleButton(this); //this is optional and you should use your way to create the button :)
if (btn.isChecked())
{
btn.setText("something");
}
else
{
btn.setText("something else");
}
Advice: you should place this validation in an onclickListener :)
Upvotes: 1