Android,Change App:SwitchCompat的主题值,以编程方式

时间:2017-01-23 10:21:47

标签: android user-interface switchcompat

我想将 app:theme 属性的SwitchCompat值更改为其他内容(@ 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"/>

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

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

enter image description here

我想要的是将主题(开关的颜色)从粉红色变为蓝色或任何反之亦然。

2 个答案:

答案 0 :(得分:3)

试试这个...我已经测试过,它的工作非常好

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

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

答案 1 :(得分:0)

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

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