Below is code to add a switch to a table layout. When the switch is touch it turns RED. I need it to be GREEN.
I have tried everything to change the ON color to green with no success.
Switch sw1 = new Switch(this);
sw1.setTag(i);
if (switchonoff.get(i).equals("true"))
{
sw1.setChecked(true);
}
else
{
sw1.setChecked(false);
}
sw1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
System.out.println("____Switch State: isChecked: " + isChecked + " " + buttonView.getTag() );
Integer tmpint = (Integer)buttonView.getTag();
if (isChecked)
{
switchonoff.set(tmpint, "true");
}
else
{
switchonoff.set(tmpint, "false");
}
for (int i=0; i<mnumberofrows; i++ )
{
System.out.println("________Switch State: isChecked " + i + " " + switchonoff.get(i));
}
}
});
The color of the switch is determined by the theme or style of your app. You will need to create a custom style and apply it to your switch. With
Edit values\styles.xml with the following
<style name="SwitchTheme" parent="Theme.AppCompat.Light">
<item name="android:colorControlActivated">#148E13</item>
</style>
Now we just need to apply it to the switch.
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Switch"
android:id="@+id/switch1"
android:theme="@style/SwitchTheme" <--- Important line
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="78dp" />
Then we are left with the following:
Before
After
This answer will help those that will be using SwitchMaterial
rather than Switch
Here's an example of a SwitchMaterial
in XML. Set a custom theme as seen in the last line of the xml
<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/switchLocks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/filter_lock_title"
android:theme="@style/FilterSwitchThemeGreen" />
In your values/styles.xml
add a style for your switch.
<style name="FilterSwitchThemeGreen" parent="AppTheme">
<item name="colorAccent">#00FF00</item>
</style>
Before:
After:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With