1

我想将 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"/>

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

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

在此处输入图像描述

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

4

2 回答 2

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

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

于 2017-01-23T11:38:58.980 回答
0

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

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

于 2017-01-23T10:48:53.723 回答