[英]Android, Change App:theme value of SwitchCompat programmatically
我想將app:theme屬性的SwitchCompat值改為其他東西(@ style / switchColorStyleBlue)。 我該如何以編程方式執行此操作? (app:主題基本上改變了切換的顏色)
<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);
我想要的是將主題(開關的顏色)從粉紅色改為藍色或任何反之亦然。
試試這個...我已經測試過,它工作得非常好
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”。
你可以試試switchCompat.setSwitchTypeface(typeface, R.style.switchColorStyleBlue);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.