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).
Related
I've seen some SO questions and they gave some possible methods to achieve what I want. For example:
Use colorControlHighlight attribute in styles.xml.
Here is my styles-v21.xml:
<style name="SelectableItemBackground">
<item name="android:colorControlHighlight">#5677FC</item>
<item name="android:background">?attr/selectableItemBackground</item>
</style>
And my widget:
<TextView
android:id="#+id/tv_take_photo_as_bt"
android:layout_width="280dp"
android:layout_height="48dp"
android:text="#string/act_take_photo"
style="#style/SelectableItemBackground"/>
And it doesn't work. I also tried to add parent="Theme.AppCompat to "SelectableItemBackground" style, or change to colorControlHighlight(no android: prefix)", or change to ?android:attr/selectableItemBackground, neither is useful.
Use backgroundTint attribute in layout.
So I add android:backgroundTint="#5677FC" to my TextView. Still useless. Then I tried to change android:backgroundTintMode to src_in and src_atop, and they never make a difference.
So, how can I change ripple color when I use ?attr/selectableItemBackground as background. I only focus on Lollipop and above. Thank you in advance!
Finally I find the solution: instead of using android:colorControlHighlight directly in theme SelectableItemBackground, I should write another style:
<style name="SelectableItemTheme">
<item name="colorControlHighlight">#color/ripple_color</item>
</style>
Then:
<style name="SelectableItemBackground">
<item name="android:theme">#style/SelectableItemTheme</item>
<item name="android:background">?attr/selectableItemBackground</item>
</style>
Finally add style="#style/SelectableItemBackground" to View in layout.xml.
UPDATED ON 2016/8/26
After N's release, I found that sometimes we cannot use this method to set ripple color for some kind of View(for example, the CardView). Now I highly recommend developers using RippleDrawable, which can also be declared in xml. Here is an example:
I want to show a ripple effect when user touches/clicks a CardView above API21, and of course there should be another kind of feedback before Lollipop. So I should write:
<android.support.v7.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:foreground="#drawable/selectable_item_background"/>
and selectable_item_background in drawable folder:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:drawable="#android:color/transparent" />
<item android:drawable="#color/color_clicked" />
</selector>
selectable_item_background in drawable-v21 folder:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/ripple_black" />
</selector>
finally, the ripple_black in drawable(or drawable-v21) folder:
<ripple
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:color="#color/color_clicked"
tools:ignore="NewApi" /> <!--you can remove this line if it's in v21 folder-->
That's it. For other views, maybe you should use android:background="#drawable/selectable_item_background". Don't forget to set an OnClickListener, OnTouchListener or something like those for them, otherwise ripple won't show.
Ripple effect on pre- and Lollipop+ devices
harrane and Liuting are right. The accepted answer is not the best way.
Let me show in code how to change ripple color for pre-Lollipop versions and higher
Your AppTheme should inherit from any AppCompat theme and contain colorControlHighlight attribute (without 'android:' prefix)
<!-- Application theme. -->
<style name="AppTheme" parent="#style/Theme.AppCompat.Light.NoActionBar">
<item name="colorControlHighlight">#40ffffff</item>
</style>
Your view should contain clickable="true" (or should have a click listener set programmatically) and background should be "?attr/selectableItemBackgroundBorderless" or "?attr/selectableItemBackground" :
<LinearLayout
...
android:clickable="true"
android:background="?attr/selectableItemBackgroundBorderless"/>
Note: that if your parent view has white background you won't see ripple effect since it's white. Change colorControlHighlight value for a different color
Also, if you want different ripple colors on different activities you can set personal theme for each activity in Manifest file, for example:
<activity
android:name="com.myapp.GalleryActivity"
android:theme="#style/RedRippleTheme"
/>
Different ripple colors for different fragments in the same activity?
You can change attributes of Activity Theme for each fragment in runtime. Just overwrite them before fragment was inflated with your custom style and apply to a current Theme:
in values/styles.xml
<style name="colorControlHighlight_blue">
<item name="colorControlHighlight">#color/main_blue_alpha26</item>
</style>
Then, in your fragment before inflation in onCreateView():
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getContext().getTheme().applyStyle(R.style.colorControlHighlight_blue, true); //blue ripple color
View view = inflater.inflate(R.layout.my_fragment_layout, container, false);
return view;
}
This style will work only for this fragment
Different ripple color for different Views? (Lollipop +)
You can change the ripple color for each view seperately using
colorControlHighlight attribute, it doesn't work if you apply them to a view directly:
<TextView
...
colorControlHighlight="#40ffffff"/> <!-- DOESN'T WORK -->
you should apply it as a theme:
<TextView
...
android:theme="#style/colorControlHighlight_blue"/>
P.S. Also, sometimes this approach helps if you have unknown issues with ripple and you can't figure it out.
In my case, I used 3rd party sliding lib which messed up ripple effects for the entire layout and adding explicitly this theme to all clickable views worked out for me.
It's showing ripple effect with color on API +21, and simple gray background on press for API -21.
Add this style:
<style name="AppTheme.MyRipple">
<item name="colorControlHighlight">#color/your_color</item>
<item name="android:background">?selectableItemBackgroundBorderless</item>
</style>
And set it to the view:
<Button
...
android:theme="#style/AppTheme.MyRipple" />
Use the below steps:
1. Make changes to button view in your layout.xml
2. Add new styles in styles.xml
your_layout.xml
<Button
android:id="#+id/setup_submit_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/action_sign_in"
android:textStyle="bold"
android:background="#color/colorPrimary"
android:textColor="#color/white"
style="#style/SelectableItemBackground"
android:foreground="?android:attr/selectableItemBackground"/>
-The style attribute calls the style that we created.
-Foreground attribute calls the andorid's default selectable attribute.
styles.xml
<style name="SelectableItemTheme">
<item name="colorControlHighlight">#color/white</item>
</style>
<style name="SelectableItemBackground">
<item name="android:theme">#style/SelectableItemTheme</item>
<item name="android:background">?attr/selectableItemBackground</item>
</style>
The accepted answer is wrong.
The correct way to use is what Liuting mentioned in the comment.
Use colorControlHighlight instead of android:colorControlHighlight for changing the default colorControlHighlight from AppCompat
* Please refer to http://android-developers.blogspot.co.uk/2014/10/appcompat-v21-material-design-for-pre.html in the Theming section *
This code works for me to create a ripple:
public static void setRippleDrawable(View view, int normalColor, int touchColor) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
RippleDrawable rippleDrawable = new RippleDrawable(ColorStateList.valueOf(touchColor), view.getBackground(), null);
view.setBackground(rippleDrawable);
} else {
StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, new ColorDrawable(touchColor));
stateListDrawable.addState(new int[]{android.R.attr.state_focused}, new ColorDrawable(touchColor));
stateListDrawable.addState(new int[]{}, new ColorDrawable(normalColor));
view.setBackground(stateListDrawable);
}
} catch (Exception e) {
Log.e(LOG_TAG, "" + e);
}
}
I did not found any way to modify the selectableItemBackground attribute.
That's why I did it like above.
In dark black theme(Or any other) app try to use like below
first create ripple_effect.xml in drawable folder and add code like
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="#f5f5f5">
<item android:id="#android:id/mask">
<shape android:shape="rectangle">
<solid android:color="#f5f5f5" />
</shape>
</item>
</ripple>
then set background to your Any view like Linear layout, Button, TextView etc.
<TextView
android:id="#+id/tvApply"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/ripple_effect"
android:clickable="true"
android:text="APPLY"
android:textColor="#FFFFFF"
android:gravity="center"
android:textSize="#dimen/_8sdp"
android:padding="#dimen/_8sdp"
android:focusable="true" />
Use the foreground attribute as selectableItemBackground
and background attribute as the color you want.
android:foreground="?attr/selectableItemBackground"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="#color/white"
I have set flat icon for all my Preference, I would like to change the color of that icon globally.
When I try the below code it even changes the back button color in the toolbar.
I want only Preference icon tint to be changed globally. Thank in advance.
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<SwitchPreference
android:id="#+id/pref_toggle_alarm"
android:icon="#drawable/ic_pref_notifications"
android:key="key_toggle_alarm"
android:summaryOff="Alarm OFF"
android:summaryOn="Alarm ON"
android:title="Alarm" />
<web.prefs.TimePrefs
android:id="#+id/pref_select_time"
android:icon="#drawable/ic_pref_time"
android:key="key_time"
android:summary="Set some time"
android:title="Select Time" />
<MultiSelectListPreference
android:id="#+id/pref_select_week"
android:defaultValue="#array/week_array_values"
android:entries="#array/array_week_selection"
android:entryValues="#array/week_array_values"
android:icon="#drawable/ic_pref_time"
android:key="key_week"
android:title="Select Days" />
<ListPreference
android:id="#+id/pref_track"
android:defaultValue="0"
android:entries="#array/tracks_arrays"
android:entryValues="#array/tracks_arrays_values"
android:icon="#drawable/ic_music_note"
android:key="key_track"
android:summary="%s"
android:title="Select Track" />
</PreferenceScreen>
style.xml
<style name="PreferencesTheme" parent="#style/AppTheme.NoActionBar">
<item name="android:textColorPrimary">#color/primary_text</item>
<item name="android:textColorSecondary">#color/secondary_text</item>
<item name="android:colorAccent">#color/accent</item>
<item name="android:tint">#color/accent</item>
</style>
Here are the solutions that I found after many tests. This implies that you use at least API 21. If you are below, I recommend using a values-v21 folder and a neutral gray color which adapts to black and white backgrounds for default file.
Solution A
One solution, if you use vector icons is to make an attribute to integrate into the XML of each image.
In values/attrs.xml :
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="iconPreferenceColor" format="reference|color" />
</resources>
In each icon add android:fillColor="?attr/iconPreferenceColor", sample :
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="?attr/iconPreferenceColor"
android:pathData="M13,2.05v3.03c3.39,0.49 6,3.39 6,6.92 0,0.9 -0.18,1.75 -0.48,2.54l2.6,1.53c0.56,-1.24 0.88,-2.62 0.88,-4.07 0,-5.18 -3.95,-9.45 -9,-9.95zM12,19c-3.87,0 -7,-3.13 -7,-7 0,-3.53 2.61,-6.43 6,-6.92V2.05c-5.06,0.5 -9,4.76 -9,9.95 0,5.52 4.47,10 9.99,10 3.31,0 6.24,-1.61 8.06,-4.09l-2.6,-1.53C16.17,17.98 14.21,19 12,19z"/>
</vector>
and in style :
<item name="iconPreferenceColor">#color/green</item>
Solution B (better)
It is possible to tint the icons directly from a style file with PreferenceThemeOverlay.v14.Material.
In values/styles.xml:
<style name="MyStyle.Night" parent="Theme.AppCompat" >
<item name="preferenceTheme">#style/MyStyle.Preference.v21</item>
...
</style>
<!-- Preference Theme -->
<style name="MyStyle.Preference.v21" parent="#style/PreferenceThemeOverlay.v14.Material">
<item name="android:tint">#color/green</item>
</style>
Please note, you must also use the android:tint parameter in the style of your toolbar, otherwise you may have bugs when changing themes dynamically.
I hope it's helpful
You have to change the color of preference icons programmatically, there's no way to do it by themes or XML attributes. You can add the following in your PreferenceFragment:
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.preferences);
int colorAttr = android.R.attr.textColorSecondary;
TypedArray ta = context.getTheme().obtainStyledAttributes(new int[]{colorAttr});
int iconColor = ta.getColor(0, 0);
ta.recycle();
tintIcons(getPreferenceScreen(), iconColor);
}
private static void tintIcons(Preference preference, int color) {
if (preference instanceof PreferenceGroup) {
PreferenceGroup group = ((PreferenceGroup) preference);
for (int i = 0; i < group.getPreferenceCount(); i++) {
tintIcons(group.getPreference(i), color);
}
} else {
Drawable icon = preference.getIcon();
if (icon != null) {
DrawableCompat.setTint(icon, color);
}
}
}
Alternatively, I think this library may also be able to help you tint icons. It also fixes other issues with AppCompat preferences.
Old question but still my answer could be valuable to someone.
None of the answers above actually worked for me because I didn't want to change the whole theme but just the icon color.
If you change the tint color in your reference style and put it into your main theme it will get buggy as it is said in answer above.
If you just want to change the icon color and nothing, NOTHING else I highly advise using different drawable resources for day and night scenarious.
In my case I have two vector drawables, one for day and one for night theme and they work just fine.
This solution does not change icons tint globally, but also does not cause issues with tint in the toolbar. Invoke this in onViewCreated() of your PreferenceFragmentCompat.
val rv = view.findViewById<RecyclerView>(androidx.preference.R.id.recycler_view)
rv?.viewTreeObserver?.addOnDrawListener {
rv.children.forEach { pref ->
val icon = pref.findViewById<View>(android.R.id.icon) as? PreferenceImageView
icon?.let {
if (it.tag != "painted") {
it.setColorFilter(
ContextCompat.getColor(requireContext(), R.color.iconColor),
PorterDuff.Mode.SRC_IN
)
it.tag = "painted"
}
}
}
}
Android Floating Action button is working fine upto OS version 5.0.1. But it is not working properly rather its becoming transparent above OS version 5.0.1. Does any one have encountered with such issue. I have to change background Tint list dynamically so defining only in xml is not use full. So how to handle it with OS above 5.0.1.
Thank you in advance for your co-operation.
Changing dynamically TintList color
mFloatingActionButtonBack.setBackgroundTintList(changeColor(getResources().getColor(R.color.color_gray)));
Xml for Floating Action Button
<android.support.design.widget.FloatingActionButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/contact_floating_btn"
app:fabSize="normal"
android:src="#drawable/contact_directions"
android:layout_alignParentRight="true"
android:clickable="true"
android:layout_below="#+id/gmap_frag"
android:layout_marginTop="#dimen/fab_margin"
android:layout_marginRight="#dimen/fab_margin_right"
/>
Style Part
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/color_primary</item>
<item name="colorPrimaryDark">#color/color_primary_dark</item>
<item name="colorAccent">#color/color_primary</item>
<item name="colorControlNormal">#d7d7d7</item>
</style>
What I found a solution to the problem I was facing is following.
if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Fab.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.color_gray)));
} else {
Fab.setBackgroundTintList(changeColor(getActivity().getResources().getColor(R.color.color_gray)));
}
and the method for ColorStateList is
public ColorStateList changeColor(int color){
ColorStateList myColorStateList = new ColorStateList(
new int[][]{
new int[]{android.R.attr.state_active},
new int[]{android.R.attr.state_window_focused},
new int[]{android.R.attr.state_pressed}, //1
new int[]{android.R.attr.state_focused}, //2
new int[]{android.R.attr.state_focused, android.R.attr.state_pressed} //3
},
new int[]{
color,
color,
color, //1
color, //2
color//3
}
);
return myColorStateList;
}
Hope this will help someone else having same issue as I had
I am using appcompat v7 to get the look consistent on Android 5 and less. It works rather well. However I cannot figure out how to change the bottom line color and the accent color for EditTexts. Is it possible?
I have tried to define a custom android:editTextStyle (cf. below) but I only succeeded to change the full background color or text color but not the bottom line nor the accent color. Is there a specific property value to use? do I have to use a custom drawable image through the android:background property? is it not possible to specify a color in hexa?
<style name="Theme.App.Base" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:editTextStyle">#style/Widget.App.EditText</item>
</style>
<style name="Widget.App.EditText" parent="Widget.AppCompat.EditText">
???
</style>
According to android API 21 sources, EditTexts with material design seem to use colorControlActivated and colorControlNormal. Therefore, I have tried to override these properties in the previous style definition but it has no effect. Probably appcompat does not use it. Unfortunately, I cannot find the sources for the last version of appcompat with material design.
Finally, I have found a solution. It simply consists of overriding the value for colorControlActivated, colorControlHighlight and colorControlNormal in your app theme definition and not your edittext style. Then, think to use this theme for whatever activity you desire. Below is an example:
<style name="Theme.App.Base" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorControlNormal">#c5c5c5</item>
<item name="colorControlActivated">#color/accent</item>
<item name="colorControlHighlight">#color/accent</item>
</style>
I felt like this needed an answer in case somebody wanted to change just a single edittext. I do it like this:
editText.getBackground().mutate().setColorFilter(ContextCompat.getColor(context, R.color.your_color), PorterDuff.Mode.SRC_ATOP);
While Laurents solution is correct, it comes with some drawbacks as described in the comments since not only the bottom line of the EditText gets tinted but the Back Button of the Toolbar, CheckBoxes etc. as well.
Luckily v22.1 of appcompat-v7 introduced some new possibilities. Now it's possible to assign a specific theme only to one view. Straight from the Changelog:
Deprecated use of app:theme for styling Toolbar. You can now use android:theme for toolbars on all API level 7 and higher devices and android:theme support for all widgets on API level 11 and higher devices.
So instead of setting the desired color in a global theme, we create a new one and assign it only to the EditText.
Example:
<style name="MyEditTextTheme">
<!-- Used for the bottom line when not selected / focused -->
<item name="colorControlNormal">#9e9e9e</item>
<!-- colorControlActivated & colorControlHighlight use the colorAccent color by default -->
</style>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/MyEditTextTheme"/>
This can be changed in XML by using:
For Reference API >= 21 compatibility use:
android:backgroundTint="#color/blue"
For backward API < 21 compatibility use:
app:backgroundTint="#color/blue"
Here is the solution for API < 21 and above
Drawable drawable = yourEditText.getBackground(); // get current EditText drawable
drawable.setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_ATOP); // change the drawable color
if(Build.VERSION.SDK_INT > 16) {
yourEditText.setBackground(drawable); // set the new drawable to EditText
}else{
yourEditText.setBackgroundDrawable(drawable); // use setBackgroundDrawable because setBackground required API 16
}
Hope it help
The accepted answer is a bit more per style basis thing, but the most efficient thing to do is to add the colorAccent attribute in your AppTheme style like this:
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorAccent">#color/colorAccent</item>
<item name="android:editTextStyle">#style/EditTextStyle</item>
</style>
<style name="EditTextStyle" parent="Widget.AppCompat.EditText"/>
The colorAccent attribute is used for widget tinting throughout the app and thus should be used for consistency
If you are using appcompat-v7:22.1.0+ you can use the DrawableCompat to tint your widgets
public static void tintWidget(View view, int color) {
Drawable wrappedDrawable = DrawableCompat.wrap(view.getBackground());
DrawableCompat.setTint(wrappedDrawable.mutate(), getResources().getColor(color));
view.setBackgroundDrawable(wrappedDrawable);
}
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="colorControlNormal">#color/colorAccent</item>
<item name="colorControlActivated">#color/colorAccent</item>
<item name="colorControlHighlight">#color/colorAccent</item>
</style>
Use:
<EditText
app:backgroundTint="#color/blue"/>
This will support pre-Lollipop devices not only +21
One quick solution for your problem is to look in yourappspackage/build/intermediates/exploded-aar/com.android.support/appcompat-v7/res/drawable/ for abc_edit_text_material.xml and copy that xml file in your drawable folder. Then you can change the colour of the 9 patch files from inside this selector, in order to match your preferences.
It's very easy just add android:backgroundTint attribute in your EditText.
android:backgroundTint="#color/blue"
android:backgroundTint="#ffffff"
android:backgroundTint="#color/red"
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#ffffff"/>
Here is a part of source code of TextInputLayout in support design library(UPDATED for version 23.2.0), which changes EditText's bottom line color in a simpler way:
private void updateEditTextBackground() {
ensureBackgroundDrawableStateWorkaround();
final Drawable editTextBackground = mEditText.getBackground();
if (editTextBackground == null) {
return;
}
if (mErrorShown && mErrorView != null) {
// Set a color filter of the error color
editTextBackground.setColorFilter(
AppCompatDrawableManager.getPorterDuffColorFilter(
mErrorView.getCurrentTextColor(), PorterDuff.Mode.SRC_IN));
}
...
}
It seems that all of above code become useless right now in 23.2.0 if you want to change the color programatically.
And if you want to support all platforms, here is my method:
/**
* Set backgroundTint to {#link View} across all targeting platform level.
* #param view the {#link View} to tint.
* #param color color used to tint.
*/
public static void tintView(View view, int color) {
final Drawable d = view.getBackground();
final Drawable nd = d.getConstantState().newDrawable();
nd.setColorFilter(AppCompatDrawableManager.getPorterDuffColorFilter(
color, PorterDuff.Mode.SRC_IN));
view.setBackground(nd);
}
I too was stuck on this problem for too long.
I required a solution that worked for versions both above and below v21.
I finally discovered a very simple perhaps not ideal but effective solution: Simply set the background colour to transparent in the EditText properties.
<EditText
android:background="#android:color/transparent"/>
I hope this saves someone some time.
For me I modified both the AppTheme and a value colors.xml Both the colorControlNormal and the colorAccent helped me change the EditText border color. As well as the cursor, and the "|" when inside an EditText.
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorControlNormal">#color/yellow</item>
<item name="colorAccent">#color/yellow</item>
</style>
Here is the colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="yellow">#B7EC2A</color>
</resources>
I took out the android:textCursorDrawable attribute to #null that I placed inside the editText style. When I tried using this, the colors would not change.
You can set background of edittext to a rectangle with minus padding on left, right and top to achieve this. Here is the xml example:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:top="-1dp"
android:left="-1dp"
android:right="-1dp"
android:bottom="1dp"
>
<shape android:shape="rectangle">
<stroke android:width="1dp" android:color="#6A9A3A"/>
</shape>
</item>
</layer-list>
Replace the shape with a selector if you want to provide different width and color for focused edittext.
I worked out a working solution to this problem after 2 days of struggle, below solution is perfect for them who want to change few edit text only, change/toggle color through java code, and want to overcome the problems of different behavior on OS versions due to use setColorFilter() method.
import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatDrawableManager;
import android.support.v7.widget.AppCompatEditText;
import android.util.AttributeSet;
import com.newco.cooltv.R;
public class RqubeErrorEditText extends AppCompatEditText {
private int errorUnderlineColor;
private boolean isErrorStateEnabled;
private boolean mHasReconstructedEditTextBackground;
public RqubeErrorEditText(Context context) {
super(context);
initColors();
}
public RqubeErrorEditText(Context context, AttributeSet attrs) {
super(context, attrs);
initColors();
}
public RqubeErrorEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initColors();
}
private void initColors() {
errorUnderlineColor = R.color.et_error_color_rule;
}
public void setErrorColor() {
ensureBackgroundDrawableStateWorkaround();
getBackground().setColorFilter(AppCompatDrawableManager.getPorterDuffColorFilter(
ContextCompat.getColor(getContext(), errorUnderlineColor), PorterDuff.Mode.SRC_IN));
}
private void ensureBackgroundDrawableStateWorkaround() {
final Drawable bg = getBackground();
if (bg == null) {
return;
}
if (!mHasReconstructedEditTextBackground) {
// This is gross. There is an issue in the platform which affects container Drawables
// where the first drawable retrieved from resources will propogate any changes
// (like color filter) to all instances from the cache. We'll try to workaround it...
final Drawable newBg = bg.getConstantState().newDrawable();
//if (bg instanceof DrawableContainer) {
// // If we have a Drawable container, we can try and set it's constant state via
// // reflection from the new Drawable
// mHasReconstructedEditTextBackground =
// DrawableUtils.setContainerConstantState(
// (DrawableContainer) bg, newBg.getConstantState());
//}
if (!mHasReconstructedEditTextBackground) {
// If we reach here then we just need to set a brand new instance of the Drawable
// as the background. This has the unfortunate side-effect of wiping out any
// user set padding, but I'd hope that use of custom padding on an EditText
// is limited.
setBackgroundDrawable(newBg);
mHasReconstructedEditTextBackground = true;
}
}
}
public boolean isErrorStateEnabled() {
return isErrorStateEnabled;
}
public void setErrorState(boolean isErrorStateEnabled) {
this.isErrorStateEnabled = isErrorStateEnabled;
if (isErrorStateEnabled) {
setErrorColor();
invalidate();
} else {
getBackground().mutate().clearColorFilter();
invalidate();
}
}
}
Uses in xml
<com.rqube.ui.widget.RqubeErrorEditText
android:id="#+id/f_signup_et_referral_code"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/referral_iv"
android:layout_toRightOf="#+id/referral_iv"
android:ems="10"
android:hint="#string/lbl_referral_code"
android:imeOptions="actionNext"
android:inputType="textEmailAddress"
android:textSize="#dimen/text_size_sp_16"
android:theme="#style/EditTextStyle"/>
Add lines in style
<style name="EditTextStyle" parent="android:Widget.EditText">
<item name="android:textColor">#color/txt_color_change</item>
<item name="android:textColorHint">#color/et_default_color_text</item>
<item name="colorControlNormal">#color/et_default_color_rule</item>
<item name="colorControlActivated">#color/et_engagged_color_rule</item>
</style>
java code to toggle color
myRqubeEditText.setErrorState(true);
myRqubeEditText.setErrorState(false);
In Activit.XML add the code
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/editText"
android:hint="Informe o usuário"
android:backgroundTint="#android:color/transparent"/>
Where BackgroundTint=color for your desired colour
I use this method to change the color of the line with PorterDuff, with no other drawable.
public void changeBottomColorSearchView(int color) {
int searchPlateId = mSearchView.getContext().getResources().getIdentifier("android:id/search_plate", null, null);
View searchPlate = mSearchView.findViewById(searchPlateId);
searchPlate.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
If you want change bottom line without using app colors, use these lines in your theme:
<item name="android:editTextStyle">#android:style/Widget.EditText</item>
<item name="editTextStyle">#android:style/Widget.EditText</item>
I don't know another solution.
I was absolutely baffled by this problem. I had tried everything in this thread, and in others, but no matter what I did I could not change the color of the underline to anything other than the default blue.
I finally figured out what was going on. I was (incorrectly) using android.widget.EditText when making a new instance (but the rest of my components were from the appcompat library). I should have used android.support.v7.widget.AppCompatEditText. I replaced new EditText(this) with new AppCompatEditText(this)
and the problem was instantly solved. It turns out, if you are actually using AppCompatEditText, it will just respect the accentColor from your theme (as mentioned in several comments above) and no additional configuration is necessary.
This is the easiest and most efficient/reusable/works on all APIs
Create a custom EditText class like so:
public class EditText extends android.widget.EditText {
public EditText(Context context) {
super(context);
init();
}
public EditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public EditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
getBackground().mutate().setColorFilter(ContextCompat.getColor(getContext(), R.color.colorAccent), PorterDuff.Mode.SRC_ATOP);
}
}
Then use it like this:
<company.com.app.EditText
android:layout_width="200dp"
android:layout_height="wrap_content"/>
To change the EditText background dynamically, you can use ColorStateList.
int[][] states = new int[][] {
new int[] { android.R.attr.state_enabled}, // enabled
new int[] {-android.R.attr.state_enabled}, // disabled
new int[] {-android.R.attr.state_checked}, // unchecked
new int[] { android.R.attr.state_pressed} // pressed
};
int[] colors = new int[] {
Color.BLACK,
Color.RED,
Color.GREEN,
Color.BLUE
};
ColorStateList colorStateList = new ColorStateList(states, colors);
Credits: This SO answer about ColorStateList is awesome.
You can use just backgroundTint for change bottom line color of edit text
android:backgroundTint="#000000"
example :
<EditText
android:id="#+id/title1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#000000" />
Add app:backgroundTint for below api level 21. Otherwise use android:backgroundTint.
For below api level 21.
<EditText
android:id="#+id/edt_name"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:textColor="#0012ff"
app:backgroundTint="#0012ff"/>
For higher than api level 21.
<EditText
android:id="#+id/edt_name"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:textColor="#0012ff"
android:backgroundTint="#0012ff"/>
Please modify this method according to your need. This worked for me!
private boolean validateMobilenumber() {
if (mobilenumber.getText().toString().trim().isEmpty() || mobilenumber.getText().toString().length() < 10) {
input_layout_mobilenumber.setErrorEnabled(true);
input_layout_mobilenumber.setError(getString(R.string.err_msg_mobilenumber));
// requestFocus(mobilenumber);
return false;
} else {
input_layout_mobilenumber.setError(null);
input_layout_mobilenumber.setErrorEnabled(false);
mobilenumber.setBackground(mobilenumber.getBackground().getConstantState().newDrawable());
}
}
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');
}
});
}