Change color of a radio button - android

I am developing an quiz based app. There will be 1 question and 4 option(radio buttons). If user select any wrong answer then I want to turn that radio button color to Red. How to do this?

Just came to show something that really help me with this:
Everyone talks about how to use the tint and how to use the colorAccent, but, this wont work on phones with API less than 21.
So, the real fix on this or at least what helped me was to use android.support.v7.widget.AppCompatRadioButton instead of RadioButton
With this on your layout, you can use:
app:buttonTint="#color/yourColor"
without getting warnings or problems about the compat of the view.
And, don't you forget about adding:
xmlns:app="http://schemas.android.com/apk/res-auto"
to your layout parent or to your widget.
Edit:
#aselims mention on a comment that there's not buttonTintin the app namespace.
So... here's my current style for this solution:
<style name="MRadioButton.Purple" parent="Widget.AppCompat.CompoundButton.RadioButton">
<item name="colorAccent">#color/youColor</item>
<item name="colorControlHighlight">#color/yourColor</item>
<item name="android:colorPressedHighlight">#color/yourColor</item>
<item name="colorPrimaryDark">#color/yourColor</item>
<item name="colorPrimary">#color/yourColor</item>
<item name="colorControlActivated">#color/yourColor</item>
</style>

The fastest thing to do is to set the buttonTint to your desired color:
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radio"
android:checked="true"
android:buttonTint="#color/your_color"/>
In your values/colors.xml put your color in this case a reddish one:
<color name="your_color">#e75748</color>
Result:
As #smashing pointed, this only will work on API level >= 21

To change RadioButton button colour programmatically, and works on api level < 21, should use AppCompatRadioButton instead of RadioButton:
(otherwise will warn setbuttontintlist requrie api level 21)
import android.support.v7.widget.AppCompatRadioButton;
AppCompatRadioButton radioButton = new AppCompatRadioButton(getActivity());
radioButton.setSupportButtonTintList(
ContextCompat.getColorStateList(getActivity(),
  R.color.single_choice_state_list));
single_choice_state_list.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:color="#color/single_choice_checked"></item>
<item android:state_checked="false" android:color="#color/single_choice_unchecked"></item>
</selector>

This site is really good for customizing Android components in general: android-holo-colors
Just choose the radio button, make the color red, download and use it in your project!

Create a selector drawable for you radio button under drawable/radio_button.xml folder and mention all the required states for your radio button.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="true"
android:state_window_focused="false"
android:drawable="#drawable/radio_button_on" />
<item
android:state_checked="false"
android:state_window_focused="false"
android:drawable="#drawable/radio_button_off" />
<item
android:state_checked="true"
android:state_pressed="true"
android:drawable="#drawable/radio_button_on_pressed" />
<item
android:state_checked="false"
android:state_pressed="true"
android:drawable="#drawable/radio_button_off_pressed" />
<item
android:state_checked="true"
android:state_focused="true"
android:drawable="#drawable/radio_button_on_selected" />
<item
android:state_checked="false"
android:state_focused="true"
android:drawable="#drawable/radio_button_off_selected" />
<item
android:state_checked="true"
android:drawable="#drawable/radio_button_on" />
<item
android:state_checked="false"
android:drawable="#drawable/radio_button_off" />
</selector>
And specify android:button="#drawable/radio_button" for your radio button
Dont forget to add the corresponding images for different states of radio button.

//get radio button reference from layout
RadioButton raPrivate = (RadioButton) layout.findViewById(R.id.radioPrivate);
//parse textColor from string hex code
int textColor = Color.parseColor("#000000");
//set textcolor to radioButton
raPrivate.setButtonTintList(ColorStateList.valueOf(textColor));
u can only assing ColorStateList objets as color for the radioButton, if u use valueOf it will only use one color.
Hope this helps :>

You can perform a backwards compatible tint on the radio button
XML:
<android.support.v7.widget.AppCompatRadioButton
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:buttonTint="#color/red"/>
Or java:
CompoundButton button = (CompoundButton) findViewById(R.id.radioButton);
CompoundButtonCompat.setButtonTintList(button, ContextCompat.getColorStateList(this, R.color.red));

Hope this helps..
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
radioButton.setButtonTintList(ContextCompat.getColorStateList(mContext, R.color.colorGris));
}else {//Do something if you have a lower version}
For me its working.

add these two properties in your style this you are using in the manifest with the activity
<item name="colorControlNormal">#color/grey</item> // for state released color
<item name="colorAccent">#color/blueLogo</item> //for state pressed color

For kotlin user
Create an extension
fun RadioButton.setCircleColor() {
val colorStateList = ColorStateList(
arrayOf(
intArrayOf(-android.R.attr.state_checked), // unchecked
intArrayOf(android.R.attr.state_checked) // checked
), intArrayOf(
Color.RED, // unchecked color
Color.GREEN // checked color
)
)
// finally set button tint list
buttonTintList = colorStateList
// optionally tint mode or tint blend
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
buttonTintBlendMode = BlendMode.SRC_IN
}else{
buttonTintMode = PorterDuff.Mode.SRC_IN
}
invalidate() // could not be necessary
}
Now call it
radioButton.setCircleColor()
done

Create an image !like this and place it in your drawable folders..
call it by,
RadioButton rb=(RadioButton) findViewById(R.id.radioButton1);
rb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
rb.setButtonDrawable(R.drawable.'you image here');
}
});
}

Related

setOnCheckedChangeListener for every radiobutton

I have a radiogroup containing several radiobuttons whose background color is grey. When I click on a radiobutton I would need the clicked one to change background color to black, while others would keep the grey background. I know I can set OnCheckedChangeListeners for all radiobuttons like this:
if(checked) then setBackGroundColor to black;
else setBackGroundColor to grey;
but is there any more efficient way to do that? Like write just one OnCheckedChangeListener for the whole group
Create a selector -> drawable/radio_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true"
android:color="#color/black" /> <!-- checked -->
<item android:state_checked="false"
android:color="#color/grey" /> <!-- unchecked -->
</selector>
And in the RadioButton view add
android:buttonTint="#drawable/radio_selector"
This works on api 21+
If you are using a lower minimum api you will need to set buttonTint in a style
<style name="radio_style" parent="Widget.AppCompat.CompoundButton.RadioButton">
<item name="buttonTint">#drawable/radio_selector</item>
</style>
and add this instead to your RadionButton
style="#style/radio_style"

How do I programmatically change the style of a Material Component Text Button in Android?

I have a material text button <Button android:id="#+id/button" style="#style/Widget.MaterialComponents.Button.TextButton"/> that I'd like to change the colour of at runtime. So I set the text colour using button.setTextColor(Color.rgb(10, 10, 10)). Unfortunately, this doesn't change the background drawable, so when I click on the button it's ripple colour is unchanged. I'm guessing I need to change the background with something like attackButton.background = getDrawable(R.drawable.ripple), but I'm not sure how to populate the ripple.xml. Does this method make sense for changing the button text colour and ripple? If so, how should I write the ripple.xml?
To change the colors in the MaterialButton you can use:
button.setBackgroundTintList to change the background tint. You should use a selector.
button.setRippleColor to change the ripple color. Also in this case you should use a selector (see below)
button.setTextColor to change the color of the text. Also in this case you should use a selector.
It is the default selector used in the ripple color:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:alpha="#dimen/mtrl_low_ripple_pressed_alpha" android:color="?attr/colorPrimary" android:state_pressed="true"/>
<item android:alpha="#dimen/mtrl_low_ripple_focused_alpha" android:color="?attr/colorPrimary" android:state_focused="true" android:state_hovered="true"/>
<item android:alpha="#dimen/mtrl_low_ripple_focused_alpha" android:color="?attr/colorPrimary" android:state_focused="true"/>
<item android:alpha="#dimen/mtrl_low_ripple_hovered_alpha" android:color="?attr/colorPrimary" android:state_hovered="true"/>
<item android:alpha="#dimen/mtrl_low_ripple_default_alpha" android:color="?attr/colorPrimary"/>
</selector>
Have you tried a RippleDrawable? Then just Button.setBackground() to different resource or even a selector xml. If a ripple with selector won't be enough for you, setting the ripple mask itself can be done
myRipple.xml
<ripple android:color="#ffff0000">
<item android:id="#android:id/myRippleMask"
android:drawable="#android:color/white" />
</ripple>
programmatically:
LayerDrawable myRipple = ContextCompat.getDrawable(context, drawable.myRipple.xml);
myRipple.setDrawableByLayerId(R.id.myRippleMask,Color.rgb(10, 10, 10));
with each mask being a different color
One line of code programmatic no resource file methods for textcolor, backgroundcolor, and ripplecolor:
MaterialButton myMaterialButton = new MaterialButton(this);
myMaterialButton.setTextColor(Color.RED);
myMaterialButton.setBackgroundColor(Color.GRAY);
myMaterialButton.setRippleColor(ColorStateList.valueOf(Color.RED));

How to update the color of checkbox in checkboxpreference programmatically?

As of now checkbox is filled with the toolbar theme color but I need to show checkbox with different color other than toolbar so I need to update checkbox color programmatically in android. How to do the same?
For Checkboxpreference you should use this:
https://stackoverflow.com/a/6042324/11549280
and
for CheckBox you should use:
Suppose your checkbox is:
Checkbox checkbox;
To create a ColorStateList programmatically,
Use
ContextCompat.getColorStateList(context, R.color.your_color);
and then
CompoundButtonCompat.setButtonTintList(checkbox, colorStateList);
Create theme to your setting activity, add this parameters to the style:
<style name="AppTheme.NoActionBar.SettingActivity" parent="AppTheme.NoActionBar">
<!--when the check box is checked --!>
<item name="colorControlNormal">#color/your-color</item>
<!--when the check box is unchecked --!>
<item name="colorControlActivated">#color/your-color</item>
</style>`
if you are using AppCompatCheckBox follow the instruction below
Use buttonTint to change color of button and color selector for above 21+ api version.
<android.support.v7.widget.AppCompatCheckBox
android:id="#+id/check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:buttonTint="#color/checkbox_filter_tint"
tools:targetApi="21"/>
res/colors/checkbox_filter_tint.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/light_gray_checkbox"
android:state_checked="false"/>
<item android:color="#color/common_red"
android:state_checked="true"/>
</selector>

Android change button style resource on click

I haven't been able to find quite what I am trying to do on SO, but I feel like it should be such a common interface need that there must be a straightforward way of accomplishing this that I'm missing.
In my style.xml I have two button styles, a standard "active" button and an "inactive" button.
<style name="ButtonStandard">
<item name="android:background">#color/colorGreen</item>
<item name="android:textColor">#android:color/white</item>
<item name="android:padding">#dimen/element_padding</item>
</style>
<style name="ButtonInactive">
<item name="android:background">#color/colorLight</item>
<item name="android:textColor">#android:color/black</item>
<item name="android:padding">#dimen/element_padding</item>
</style>
I am setting one button to ButtonStandard and the other to ButtonInactive. When I click the inactive button, I want to change it to use the ButtonStandard type and vice versa. I don't want to programmatically set the styles individually in case I decide to later change the button styles and it would be unreliable to have to change it in every location.
activeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activeButton.[somehowsetstyle](R.style.ButtonInactive);
inactiveButton.[somehowsetstyle](R.style.ButtonStandard);
}
});
How can I change between these styles when users click on buttons? The most important is to not have to set specific styles within the code which is just a last resort imho.
Thanks!
Solution Notes
Generally I followed the solution below but instead I created the selector as a drawable and used android:drawable instead because it seems the button background needs that, even if just specifying a color. I also used state_activated rather than enabled so that it is only changing the look of the button and doesn't prevent clicks.
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="false"
android:drawable="#color/colorPrimaryDark" />
<item android:state_activated="true"
android:drawable="#color/colorGreen" />
<item android:drawable="#color/colorGreen" />
In XML
android:background="#drawable/selector_btn_bkg"
android:state_activated="false"
In Java
myButton.setActivated(true);
What you are looking for is ColorStateList
drawable/my_selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:color="#color/enabled_color"/>
<item android:color="#color/enabled_color"
android:state_enabled = "true"/>
<item android:color="#color/disbaled_color"
android:state_enabled = "false"/>
</selector>
my_view.xml
...
<Button
android:id="#+id/my_button"
android:enabled="false"
android:background="#drawable/my_selector"/>
Java code
onClick(View v){
myButton.setEnabled(true);
}

Change "on" color of a Switch

I'm using a standard Switch control with the holo.light theme in a ICS app.
I want to change the highlighted or on state color of the Toggle Button from the standard light blue to green.
This should be easy, but I can't seem to work out how to do it.
Late to party but this is how I did
Style
<style name="SCBSwitch" parent="Theme.AppCompat.Light">
<!-- active thumb & track color (30% transparency) -->
<item name="colorControlActivated">#46bdbf</item>
<!-- inactive thumb color -->
<item name="colorSwitchThumbNormal">#f1f1f1
</item>
<!-- inactive track color (30% transparency) -->
<item name="android:colorForeground">#42221f1f
</item>
</style>
Colors
Layout
<android.support.v7.widget.SwitchCompat
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:checked="false"
android:theme="#style/SCBSwitch" />
Result
See change of colors for enables and disabled switch
As of now it is better to use SwitchCompat from the AppCompat.v7 library. You can then use simple styling to change the color of your components.
values/themes.xml:
<style name="Theme.MyTheme" parent="Theme.AppCompat.Light">
<!-- colorPrimary is used for the default action bar background -->
<item name="colorPrimary">#color/my_awesome_color</item>
<!-- colorPrimaryDark is used for the status bar -->
<item name="colorPrimaryDark">#color/my_awesome_darker_color</item>
<!-- colorAccent is used as the default value for colorControlActivated,
which is used to tint widgets -->
<item name="colorAccent">#color/accent</item>
<!-- You can also set colorControlNormal, colorControlActivated
colorControlHighlight, and colorSwitchThumbNormal. -->
</style>
ref: Android Developers Blog
EDIT:
The way in which it should be correctly applied is through android:theme="#style/Theme.MyTheme"
and also this can be applied to parent styles such as EditTexts, RadioButtons, Switches, CheckBoxes and ProgressBars:
<style name="My.Widget.ProgressBar" parent="Widget.AppCompat.ProgressBar">
<style name="My.Widget.Checkbox" parent="Widget.AppCompat.CompoundButton.CheckBox">
As an addition to existing answers: you can customize thumb and track using selectors in res/color folder, for example:
switch_track_selector
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/lightBlue"
android:state_checked="true" />
<item android:color="#color/grey"/>
</selector>
switch_thumb_selector
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/darkBlue"
android:state_checked="true" />
<item android:color="#color/white"/>
</selector>
Use these selectors to customize track and thumb tints:
<androidx.appcompat.widget.SwitchCompat
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:trackTint="#color/switch_track_selector"
app:thumbTint="#color/switch_thumb_selector"/>
Keep in mind that if you use standart Switch and android namespace for these attributes, it will only work for API 23 and later, so use SwitchCompat with app namespace xmlns:app="http://schemas.android.com/apk/res-auto" as universal solution.
Result:
This is working for me (requires Android 4.1):
Switch switchInput = new Switch(this);
int colorOn = 0xFF323E46;
int colorOff = 0xFF666666;
int colorDisabled = 0xFF333333;
StateListDrawable thumbStates = new StateListDrawable();
thumbStates.addState(new int[]{android.R.attr.state_checked}, new ColorDrawable(colorOn));
thumbStates.addState(new int[]{-android.R.attr.state_enabled}, new ColorDrawable(colorDisabled));
thumbStates.addState(new int[]{}, new ColorDrawable(colorOff)); // this one has to come last
switchInput.setThumbDrawable(thumbStates);
Note that the "default" state needs to be added last as shown here.
The only problem I see is that the "thumb" of the switch now appears larger than the background or "track" of the switch. I think that's because I'm still using the default track image, which has some empty space around it. However, when I attempted to customize the track image using this technique, my switch appeared to have a height of 1 pixel with just a sliver of the on/off text appearing. There must be a solution for that, but I haven't found it yet...
Update for Android 5
In Android 5, the code above makes the switch disappear completely. We should be able to use the new setButtonTintList method, but this seems to be ignored for switches. But this works:
ColorStateList buttonStates = new ColorStateList(
new int[][]{
new int[]{-android.R.attr.state_enabled},
new int[]{android.R.attr.state_checked},
new int[]{}
},
new int[]{
Color.BLUE,
Color.RED,
Color.GREEN
}
);
switchInput.getThumbDrawable().setTintList(buttonStates);
switchInput.getTrackDrawable().setTintList(buttonStates);
Update for Android 6-7
As Cheruby stated in the comments, we can use the new setThumbTintList and that worked as expected for me. We can also use setTrackTintList, but that applies the color as a blend, with a result that's darker than expected in dark color themes and lighter than expected in light color themes, sometimes to the point of being invisible. In Android 7, I was able to minimize that change that by overriding the track tint mode, but I couldn't get decent results from that in Android 6. You might need to define extra colors that compensate for the blending. (Do you ever get the feeling that Google doesn't want us to customize the appearance of our apps?)
ColorStateList thumbStates = new ColorStateList(
new int[][]{
new int[]{-android.R.attr.state_enabled},
new int[]{android.R.attr.state_checked},
new int[]{}
},
new int[]{
Color.BLUE,
Color.RED,
Color.GREEN
}
);
switchInput.setThumbTintList(thumbStates);
if (Build.VERSION.SDK_INT >= 24) {
ColorStateList trackStates = new ColorStateList(
new int[][]{
new int[]{-android.R.attr.state_enabled},
new int[]{}
},
new int[]{
Color.GRAY,
Color.LTGRAY
}
);
switchInput.setTrackTintList(trackStates);
switchInput.setTrackTintMode(PorterDuff.Mode.OVERLAY);
}
To change Switch style without using style.xml or Java code, you can customize switch into layout XML :
<Switch
android:id="#+id/checkbox"
android:layout_width="wrap_content"
android:thumbTint="#color/blue"
android:trackTint="#color/white"
android:checked="true"
android:layout_height="wrap_content" />
It's attribute android:thumbTint and android:trackTint that allowed you to customize color
This is the visual result for this XML :
make drawable "newthumb.xml"
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/Green" android:state_checked="true"/>
<item android:color="#color/Red" android:state_checked="false"/>
</selector>
and make drawable "newtrack.xml"
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/black" android:state_checked="true"/>
<item android:color="#color/white" android:state_checked="false"/>
</selector>
and add it in Switch:
<Switch
android:trackTint="#drawable/newtrack"
android:thumbTint="#drawable/newthumb"
/>
Use app:trackTint and app:thumbTint instead for switch compat androidx – see #Ehsan Rosdi's comments.
Also, it's perfectly OK to make only one drawable file ("switchcolors.xml") and use that for both trackTint and thumbTint.
Create a custom Switch and override setChecked to change color:
public class SwitchPlus extends Switch {
public SwitchPlus(Context context) {
super(context);
}
public SwitchPlus(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SwitchPlus(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
public void setChecked(boolean checked) {
super.setChecked(checked);
changeColor(checked);
}
private void changeColor(boolean isChecked) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
int thumbColor;
int trackColor;
if(isChecked) {
thumbColor = Color.argb(255, 253, 153, 0);
trackColor = thumbColor;
} else {
thumbColor = Color.argb(255, 236, 236, 236);
trackColor = Color.argb(255, 0, 0, 0);
}
try {
getThumbDrawable().setColorFilter(thumbColor, PorterDuff.Mode.MULTIPLY);
getTrackDrawable().setColorFilter(trackColor, PorterDuff.Mode.MULTIPLY);
}
catch (NullPointerException e) {
e.printStackTrace();
}
}
}
}
<androidx.appcompat.widget.SwitchCompat
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:thumbTint="#color/white"
app:trackTint="#drawable/checker_track"/>
And inside checker_track.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/lightish_blue" android:state_checked="true"/>
<item android:color="#color/hint" android:state_checked="false"/>
</selector>
While answer by SubChord is correct, is doesnt really answer the question of how to set the "on" color without also affecting other widgets. To do this, use a ThemeOverlay in styles.xml:
<style name="ToggleSwitchTheme" parent="ThemeOverlay.AppCompat.Light">
<item name="colorAccent">#color/green_bright</item>
</style>
And reference it in your switch:
<android.support.v7.widget.SwitchCompat
android:theme="#style/ToggleSwitchTheme" ... />
In so doing it will ONLY affect the color of the views you want to apply it to.
I solved it by updating the Color Filter when the Switch was state was changed...
public void bind(DetailItem item) {
switchColor(item.toggle);
listSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
switchColor(b);
}
});
}
private void switchColor(boolean checked) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
listSwitch.getThumbDrawable().setColorFilter(checked ? Color.BLACK : Color.WHITE, PorterDuff.Mode.MULTIPLY);
listSwitch.getTrackDrawable().setColorFilter(!checked ? Color.BLACK : Color.WHITE, PorterDuff.Mode.MULTIPLY);
}
}
May be its a bit late, but for switch buttons, toogle button is not the answer, you must change the drawable in the xml parameter of the switch:
android:thumb="your drawable here"
In Android Lollipop and above, define it in your theme style:
<style name="BaseAppTheme" parent="Material.Theme">
...
<item name="android:colorControlActivated">#color/color_switch</item>
</style>
This worked for me -:
1.code in values/styles.xml -:
<style name="SwitchTheme" parent="Theme.AppCompat.Light">
<item name="android:colorControlActivated">#148E13</item>
</style>
2.add following line of code in your switch in your layout file -:
android:theme="#style/SwitchTheme"
Create your own 9-patch image and set it as the background of the toggle button.
http://radleymarx.com/2011/simple-guide-to-9-patch/
The solution suggested from arlomedia worked for me.
About his issue of extraspace I solved removing all the paddings to the switch.
EDIT
As requested, here what I have.
In the layout file, my switch is inside a linear layout and after a TextView.
<LinearLayout
android:id="#+id/myLinearLayout"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal|center"
android:gravity="right"
android:padding="10dp"
android:layout_marginTop="0dp"
android:background="#drawable/bkg_myLinearLayout"
android:layout_marginBottom="0dp">
<TextView
android:id="#+id/myTextForTheSwitch"
android:layout_height="wrap_content"
android:text="#string/TextForTheSwitch"
android:textSize="18sp"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal|center"
android:gravity="right"
android:layout_width="wrap_content"
android:paddingRight="20dp"
android:textColor="#color/text_white" />
<Switch
android:id="#+id/mySwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="#string/On"
android:textOff="#string/Off"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:layout_toRightOf="#id/myTextForTheSwitch"
android:layout_alignBaseline="#id/myTextForTheSwitch"
android:gravity="right" />
</LinearLayout>
Since I'm working with Xamarin / Monodroid (min. Android 4.1) my code is:
Android.Graphics.Color colorOn = Android.Graphics.Color.Green;
Android.Graphics.Color colorOff = Android.Graphics.Color.Gray;
Android.Graphics.Color colorDisabled = Android.Graphics.Color.Green;
StateListDrawable drawable = new StateListDrawable();
drawable.AddState(new int[] { Android.Resource.Attribute.StateChecked }, new ColorDrawable(colorOn));
drawable.AddState(new int[] { -Android.Resource.Attribute.StateEnabled }, new ColorDrawable(colorDisabled));
drawable.AddState(new int[] { }, new ColorDrawable(colorOff));
swtch_EnableEdit.ThumbDrawable = drawable;
swtch_EnableEdit is previously defined like this (Xamarin):
Switch swtch_EnableEdit = view.FindViewById<Switch>(Resource.Id.mySwitch);
I don't set at all the paddings and I don't call .setPadding(0, 0, 0, 0).
Easiest way is defining track tint, and setting tint mode to src_over to remove 30% transparency.
android:trackTint="#drawable/toggle_style"
android:trackTintMode="src_over"
toggle_style.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/informationDefault"
android:state_checked="true"
/>
<item android:color="#color/textDisabled" android:state_checked="false"/>
</selector>
you can make custom style for switch widget
that use color accent as a default when do custom style for it
<style name="switchStyle" parent="Theme.AppCompat.Light">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorPrimary</item> <!-- set your color -->
</style>
You can try this lib, easy to change color for the switch button.
https://github.com/kyleduo/SwitchButton
Try to find out right answer here: Selector on background color of TextView.
In two words you should create Shape in XML with color and then assign it to state "checked" in your selector.
I dont know how to do it from java , But if you have a style defined for your app you can add this line in your style and you will have the desired color for me i have used #3F51B5
<color name="ascentColor">#3F51B5</color>
In xml , you can change the color as :
<androidx.appcompat.widget.SwitchCompat
android:id="#+id/notificationSwitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="true"
app:thumbTint="#color/darkBlue"
app:trackTint="#color/colorGrey"/>
Dynamically you can change as :
Switch.thumbDrawable.setColorFilter(ContextCompat.getColor(requireActivity(), R.color.darkBlue), PorterDuff.Mode.MULTIPLY)
Based on a combination of a few of the answers here this is what worked for me.
<Switch
android:trackTintMode="src_over"
android:thumbTint="#color/white"
android:trackTint="#color/shadow"
android:checked="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Change the tint colour for track and thumb drawable.
switch.getThumbDrawable().setTint(ContextCompat.getColor(this,R.color.colorAccent));
switch.getTrackDrawable().setTint(ContextCompat.getColor(this,R.color.colorAccent));
Programattically if you want to change Switch Component Color use this code below:
binding.switchCompatBackupMedia.thumbTintList =
ColorStateList.valueOf(Color.parseColor("#00C4D3"))
binding.switchCompatBackupMedia.trackTintList =
ColorStateList.valueOf(Color.parseColor("#00C4D31F"))
Android 2022 - most simple and straightforward method:
change in
/res/values/themes.xml
FROM
<!-- Secondary brand color. -->
<item name="colorSecondary">#color/teal_200</item>
<item name="colorSecondaryVariant">#color/teal_700</item>
TO
<!-- Secondary brand color. -->
<item name="colorSecondary">#color/purple_500</item>
<item name="colorSecondaryVariant">#color/purple_700</item>
Solution for Android Studio 3.6:
yourSwitch.setTextColor(getResources().getColor(R.color.yourColor));
Changes the text color of a in the color XML file defined value (yourColor).

Categories

Resources