Reputation: 283
I created switch in code, not in xml.
Switch sw = new Switch(getActivity());
sw.setGravity(Gravity.RIGHT|Gravity.CENTER_VERTICAL);
sw.setTextOn(getString(R.string.ok));
sw.setTextOff(getString(R.string.remove));
sw.setSwitchMinWidth((int) (4.8 * pixels));
sw.setSwitchTypeface(font);
sw.setThumbResource(R.drawable.thumb);
Method setThumbResource is working well, but the method setTrackResource leads to the disappearence of switch.
My xml files for thumb and for track. They are almost the same.
thumb.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<corners
android:bottomLeftRadius="10dp"
android:bottomRightRadius="10dp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp" />
<solid android:color="#a79d90" />
</shape>
track.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<corners
android:bottomLeftRadius="10dp"
android:bottomRightRadius="10dp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp" />
<solid android:color="#bfb5a7" />
</shape>
Also, what I want to do is to set different colors for TextOn (green) and TextOff (red). I found only one method - setTextColor that leads to changing both colors.
Upvotes: 0
Views: 3672
Reputation: 6973
Hi I have posted answer on this link this worked for me.
code from there:
if (isChecked) {
mSwtPrivacyView.getTrackDrawable().setColorFilter(ContextCompat.getColor(this, R.color.switch_track_checked_true_color), PorterDuff.Mode.SRC_IN);
} else {
mSwtPrivacyView.getTrackDrawable().setColorFilter(ContextCompat.getColor(this, R.color.switch_track_checked_false_color), PorterDuff.Mode.SRC_IN);
}
Upvotes: 1
Reputation: 283
For @DjimOnDev. I'm using this
Switch sw = new Switch(getActivity());
sw.setGravity(Gravity.RIGHT|Gravity.CENTER_VERTICAL);
sw.setTextOn(getString(R.string.ok));
sw.setTextOff(getString(R.string.remove));
if (sw.isChecked()) {
sw.setSwitchTextAppearance(getActivity(), R.style.SwitchTextAppearance1);
}
else {
sw.setSwitchTextAppearance(getActivity(), R.style.SwitchTextAppearance2);
}
sw.setSwitchMinWidth((int) (3.6 * pixels));
sw.setThumbResource(R.drawable.thumb);
sw.setTrackResource(R.drawable.track);
sw.setSwitchTypeface(font);
thumb.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="#bfb5a7" />
</shape>
track.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/thumb_off" />
<item android:drawable="@drawable/thumb_default" />
styles.xml
<style name="SwitchTextAppearance1">
<item name="android:textColor">#5db701</item>
</style>
<style name="SwitchTextAppearance2">
<item name="android:textColor">#ea3d3d</item>
</style>
Upvotes: 0