Vipin Kumar
Vipin Kumar

Reputation: 93

Nothing happens when I press the switch

I have the following code that should display different text based on whether the switch is on or off. But nothing is displayed on the switch when I press the switch.

MainActivity.java

package com.hfad.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Switch;


public class MainActivity extends Activity {
    Switch sw;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sw=(Switch)findViewById(R.id.switchdemo);

        sw.setOnCheckedChangeListener(
                new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isChecked) {
                            sw.setTextOn("This switch is: on");
                        }
                        else {
                            sw.setTextOff("This switch is: off");
                        }
                    }
                }
        );
    }

}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">
   <Switch
       android:id="@+id/switchdemo"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
   />
</LinearLayout>

Upvotes: 0

Views: 90

Answers (2)

techroid
techroid

Reputation: 477

Simply replace

sw.setTextOn("This switch is: on");

with

sw.setText("This switch is: on");

and

sw.setTextOff("This switch is: off");

with

sw.setText("This switch is: off");

its working.

Upvotes: 0

Ben
Ben

Reputation: 1061

Switch doesn't support setTextOn / setTextOff at run time.

There is a hacky work around:

You need a class that extends switch and use this:

@Override
public void requestLayout() {
IslLog.i(TAG, "requestLayout");
try {
    java.lang.reflect.Field mOnLayout = Switch.class.getDeclaredField("mOnLayout");
    mOnLayout.setAccessible(true);
    mOnLayout.set(this, null);
    java.lang.reflect.Field mOffLayout = Switch.class.getDeclaredField("mOffLayout");
    mOffLayout.setAccessible(true);
    mOffLayout.set(this, null);
} catch (Exception x) {
    Log.e(TAG, x.getMessage(), x);
}
super.requestLayout();
}

then implement that class & use this:

 sw.setTextOn("Whatever");
 sw.requestLayout();

Upvotes: 1

Related Questions