Reputation: 165
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));
}
}
});
Upvotes: 11
Views: 41843
Reputation: 5104
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>
Upvotes: 5
Reputation: 103
Another way to do, change the background color:
setBackgroundColor(android.graphics.Color.GREEN);
As:
holper.aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
buttonView.setBackgroundColor(android.graphics.Color.GREEN);
}
}
Upvotes: -1
Reputation: 3408
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
Upvotes: 46