Ahmad Shahwaiz
Ahmad Shahwaiz

Reputation: 1492

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.

Upvotes: 1

Views: 2896

Answers (2)

Niharika
Niharika

Reputation: 1198

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.

Upvotes: 6

Niharika
Niharika

Reputation: 1198

You can try switchCompat.setSwitchTypeface(typeface, R.style.switchColorStyleBlue);

Ref:- https://developer.android.com/reference/android/support/v7/widget/SwitchCompat.html#setSwitchTypeface(android.graphics.Typeface,%20int)

Upvotes: 0

Related Questions