Search code examples
androiduser-interfaceswitchcompat

Android, Change App:theme value of SwitchCompat programmatically


I want to change the app:theme attribute's value of SwitchCompat to something else (@style/switchColorStyleBlue). How can I do that programmatically? (app:theme basically changes the color of toggle)

<android.support.v7.widget.SwitchCompat
android:id="@+id/switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:theme="@style/switchColorStylePink"/>

I have tried this code but its not showing appropriate results:

    SwitchCompat switchCompat = new SwitchCompat(this);
    switchCompat.setId(i);
    switchCompat.setSwitchTextAppearance(getApplicationContext(), R.style.switchColorStylePink);
    switchCompat.setChecked(false);
    containerRelativeLayout.addView(switchCompat);

enter image description here

What I want is to change the theme (color of the switch) from pink to blue or whatever viceversa.


Solution

  • Try this... I have tested and it is working perfectly fine

    public class MainActivity extends AppCompatActivity {
    
        int[][] states = new int[][] {
                new int[] {-android.R.attr.state_checked},
                new int[] {android.R.attr.state_checked},
        };
    
        int[] thumbColors = new int[] {
                Color.BLACK,
                Color.RED,
        };
    
        int[] trackColors = new int[] {
                Color.GREEN,
                Color.BLUE,
        };
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            SwitchCompat switchCompat = (SwitchCompat) findViewById(R.id.switch);
            DrawableCompat.setTintList(DrawableCompat.wrap(switchCompat.getThumbDrawable()), new ColorStateList(states, thumbColors));
            DrawableCompat.setTintList(DrawableCompat.wrap(switchCompat.getTrackDrawable()), new ColorStateList(states, trackColors));
        }
    }
    

    You will only need to update the "trackColors" and the "thumbColor" as per you requirement/needs.