Android,以编程方式更改应用程序:SwitchCompat 的主题值

Ahm*_*aiz 1 user-interface android switchcompat

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

<android.support.v7.widget.SwitchCompat
android:id="@+id/switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:theme="@style/switchColorStylePink"/>
Run Code Online (Sandbox Code Playgroud)

我试过这段代码,但它没有显示适当的结果:

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

在此处输入图片说明

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

Nih*_*ika 5

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

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

您只需要根据您的要求/需要更新“trackColors”和“thumbColor”。