user788511
user788511

Reputation: 1736

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.

Upvotes: 2

Views: 3986

Answers (3)

Dave
Dave

Reputation: 6104

Use ToggleButton.setTextOn(String) and ToggleButton.setTextOff(String)

Upvotes: 3

ilango j
ilango j

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

Aurelian Cotuna
Aurelian Cotuna

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

Related Questions