Android,以编程方式更改 SwitchCompat 的 App:theme 值

Android, Change App:theme value of SwitchCompat programmatically

我想将 SwitchCompat 的 app:theme 属性值更改为其他值 (@style/switchColorStyleBlue)。我怎样才能以编程方式做到这一点? (app:theme 基本上改变了 toggle 的颜色)

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

我试过这段代码,但没有显示正确的结果:

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

我想要的是将主题(开关的颜色)从粉红色更改为蓝色,反之亦然。

你可以试试switchCompat.setSwitchTypeface(typeface, R.style.switchColorStyleBlue);

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

试试这个...我已经测试过,它工作得很好

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));
    }
}

您只需根据 requirement/needs 更新 "trackColors" 和 "thumbColor"。