implement "android:textOff" & "android:textOn" property for toggle button programatically in Android
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.
Use ToggleButton.setTextOn(String)
and ToggleButton.setTextOff(String)
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 :)
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
}
}
});
精彩评论