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());
}
}
Related
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"
}
}
}
}
I'm moving from a custom MediaRouteButton to one inside the action-bar but it doesn't display properly. The button when custom was white which is what I wanted. However, the button is still white (and barely visible) on the action-bar even though the action-bar is of "Holo.Light" style. The button should be dark.
The button is created as an XML menu item:
<item
android:id="#+id/menu_item_media_route"
android:title="#string/menu_item_media_route"
android:actionViewClass="android.support.v7.app.MediaRouteButton"
android:actionProviderClass="android.support.v7.app.MediaRouteActionProvider"
android:showAsAction="always" />
My app is of style "#style/AppTheme":
<style name="AppTheme" parent="android:Theme.Holo.Light">
</style>
My activity of of theme "#style/FullscreenActionbarTheme":
<style name="FullscreenActionbarTheme" parent="android:Theme.Holo.Light">
<item name="android:windowFullscreen">true</item>
<item name="android:windowActionBarOverlay">true</item>
<item name="android:windowContentOverlay">#null</item>
<item name="android:windowBackground">#null</item>
<item name="android:actionBarStyle">#style/FullscreenActionbar</item>
</style>
<style name="FullscreenActionbar" parent="#android:style/Widget.Holo.Light.ActionBar.Solid">
</style>
I have no custom "ic_media_route_(on|off).png" drawables -- I used to but removed them.
I've tried changing various styles and though the action-bar will turn dark, the cast button is always white. (As it should be on a dark action bar but not a light one.)
The button is fully functional, just the wrong color. The "chooser" dialog that appears when I press the button is styled "Holo.Light".
So why is my cast button colored white on a "Holo.Light" theme as though it was a "Holo" (dark) theme?
Taken from: Link
Caution: When implementing an activity that provides a media router
interface you must extend either ActionBarActivity or FragmentActivity
from the Android Support Library, even if your android:minSdkVersion
is API 11 or higher.
ActionBarActivity has been superseded by AppCompatActivity, so you should use that instead.
Support-V7 MediaRouteButton depends on this. Look at the super call:
public MediaRouteButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(MediaRouterThemeHelper.createThemedContext(context), attrs, defStyleAttr);
....
....
}
MediaRouterThemeHelper.createThemedContext(Context):
public static Context createThemedContext(Context context) {
boolean isLightTheme = isLightTheme(context);
return new ContextThemeWrapper(context, isLightTheme ?
R.style.Theme_MediaRouter_Light : R.style.Theme_MediaRouter);
}
isLightTheme is set by resolving R.attr.isLightTheme <<== This is a support library attribute. It will not be present when your parent theme is provided by the framework, as is the case with android:Theme.Holo.Light.
private static boolean isLightTheme(Context context) {
TypedValue value = new TypedValue();
return context.getTheme().resolveAttribute(R.attr.isLightTheme, value, true)
&& value.data != 0;
}
So, isLightTheme is false & you get the dark-theme version of MediaRouteButton ==> ... always white.
Note that the Caution statement implies that your parent theme must be an AppCompat theme - AppCompatActivity (or ActionBarActivity) can't work with android:Theme.*.
Edit:
A lot of discussion took place here: Link
One can go through the chat-log to read on the approaches tried. In the end, it seems that the media-router support library needs some work to be production-ready. Read more here: MediaRouteActionProvider connection dialog theme.
If all else fails you can change the color programmatically in onCreate():
ImageButton button = ((ImageButton) toolbar.getChildAt( ... )); // The view index of the button
button.setColorFilter(Color.BLACK, PorterDuff.Mode.MULTIPLY);
I've noticed that using AppCompat themes, default toolbar icons get tinted by the attribute colorControlNormal in my style.
<style name="MyTheme" parent="Theme.AppCompat">
<item name="colorControlNormal">#color/yellow</item>
</style>
As you can see above, however, it does not happen with all icons. I provided the "plus" sign, which I got from the official icons, and it does not get tinted (I used the "white" version of the png). From what I have understood from this question, system tints only icons with just an alpha channel. Is this true?
If so: Is there a place where I can find alpha-defined, official material icons? If not - and if Toolbar icons need to be alpha-only to be tinted - how is Google expecting us to use provided icons in a Toolbar?
Somewhere in the SDK I found some icons ending in _alpha.png, and they actually get tinted well. However I need the full set of material icons, and from the official sources I could only find white, grey600 and black ones.
Applying a ColorFilter at runtime would be slightly painful, and my actual Toolbar - with some icons tinted, some others not - looks quite bad.
Another option is to use the new support for vector drawables in the support library.
See res/xml/ic_search.xml in blog post AppCompat — Age of the vectors
Notice the reference to ?attr/colorControlNormal
<vector xmlns:android="..."
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0"
android:tint="?attr/colorControlNormal">
<path
android:pathData="..."
android:fillColor="#android:color/white"/>
</vector>
Here is the solution that I use. Call tintAllIcons after onPrepareOptionsMenu or the equivalent location. The reason for mutate() is if you happen to use the icons in more than one location; without the mutate, they will all take on the same tint.
public class MenuTintUtils {
public static void tintAllIcons(Menu menu, final int color) {
for (int i = 0; i < menu.size(); ++i) {
final MenuItem item = menu.getItem(i);
tintMenuItemIcon(color, item);
tintShareIconIfPresent(color, item);
}
}
private static void tintMenuItemIcon(int color, MenuItem item) {
final Drawable drawable = item.getIcon();
if (drawable != null) {
final Drawable wrapped = DrawableCompat.wrap(drawable);
drawable.mutate();
DrawableCompat.setTint(wrapped, color);
item.setIcon(drawable);
}
}
private static void tintShareIconIfPresent(int color, MenuItem item) {
if (item.getActionView() != null) {
final View actionView = item.getActionView();
final View expandActivitiesButton = actionView.findViewById(R.id.expand_activities_button);
if (expandActivitiesButton != null) {
final ImageView image = (ImageView) expandActivitiesButton.findViewById(R.id.image);
if (image != null) {
final Drawable drawable = image.getDrawable();
final Drawable wrapped = DrawableCompat.wrap(drawable);
drawable.mutate();
DrawableCompat.setTint(wrapped, color);
image.setImageDrawable(drawable);
}
}
}
}
}
This won't take care of the overflow, but for that, you can do this:
Layout:
<android.support.v7.widget.Toolbar
...
android:theme="#style/myToolbarTheme" />
Styles:
<style name="myToolbarTheme">
<item name="colorControlNormal">#FF0000</item>
</style>
This works as of appcompat v23.1.0.
I actually was able to do this on API 10 (Gingerbread) and it worked very well.
Edit: It worked on API 22 also...
Here's the final result.
Note: The icon is a drawable resource in the drawable folder(s).
Now here's how its done:
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem item = menu.findItem(R.id.action_refresh);
Drawable icon = getResources().getDrawable(R.drawable.ic_refresh_white_24dp);
icon.setColorFilter(getResources().getColor(R.color.colorAccent), PorterDuff.Mode.SRC_IN);
item.setIcon(icon);
}
At this point you can change it to any color you want!
That's the final and true answer
First create style for toolbar like this:
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" >
<item name="iconTint">#color/primaryTextColor</item>
<!--choice your favorite color-->
</style>
Then in your main app or activity theme add this line
<item name="actionBarPopupTheme">#style/AppTheme.PopupOverlay</item>
And finally in you'r layout file add this line to toolbar
android:theme="?attr/actionBarPopupTheme"
And Then you will see your toolbar icons colored in your favorite color
I see this question is getting some views so I'm going to post an answer for those who don't read the comments.
My conjectures in the question were all wrong and it is not a matter of alpha channels, at least not externally. The fact is simply that, quoting #alanv ,
AppCompat only tints its own icons. For now, you will need to manually
tint any icons that you're providing separately from AppCompat.
This might change in the future but also might not. From this answer you can also see the list of icons (they all belong to the internal resource folder of appcompat, so you can't change them) that are automatically tinted and with which color.
Personally I use a colorControlNormal which is black or white (or similar shades), and import the icons with that particular color. Colored icons on a colored background look a little bad. However, another solution I found pleasant is this class on github. You just call MenuColorizer.colorMenu() when you create the menu.
You could just create a custom Toolbar that uses your tint color when inflating the menu.
public class MyToolbar extends Toolbar {
... some constructors, extracting mAccentColor from AttrSet, etc
#Override
public void inflateMenu(#MenuRes int resId) {
super.inflateMenu(resId);
Menu menu = getMenu();
for (int i = 0; i < menu.size(); i++) {
MenuItem item = menu.getItem(i);
Drawable icon = item.getIcon();
if (icon != null) {
item.setIcon(applyTint(icon));
}
}
}
void applyTint(Drawable icon){
icon.setColorFilter(
new PorterDuffColorFilter(mAccentColor, PorterDuff.Mode.SRC_IN)
);
}
}
Just make sure you call in your Activity/Fragment code:
toolbar.inflateMenu(R.menu.some_menu);
toolbar.setOnMenuItemClickListener(someListener);
No reflection, no view lookup, and not so much code, huh?
And don't use onCreateOptionsMenu/onOptionsItemSelected, if you use this approach
For sdk 23 or higher:
<style name="AppThemeToolbar" parent="MyAppTheme">
....
<item name="android:drawableTint">#color/secondaryLightColor</item>
</style>
My toolbar
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:theme="#style/AppThemeToolbar"
android:layout_width="match_parent"
android:layout_height="attr/actionBarSize">
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
With androidX you can define your Toolbar like this
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:theme="#style/Toolbar" />
Then, extend an AppCompat theme and set colorControlNormal property as you like:
<style name="Toolbar" parent="Theme.AppCompat.Light">
<item name="colorControlNormal">#color/colorBaseWhite</item>
<item name="android:background">#color/colorPrimary</item>
</style>
This can be done in Kotlin with:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
menu.getItem(0)?.icon?.setTint(Color.WHITE)
}
else {
#Suppress("DEPRECATION")
menu.getItem(0)?.icon?.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN)
}
It should work on all modern versions of Android, and will fail without a crash if getItem or icon returns null.
try this ... 😊
menu.getItem(0).getIcon().setTint(Color.parseColor("#22CC34"));
#NonNull
public static Drawable setTintDrawable(#NonNull Drawable drawable, #ColorInt int color) {
drawable.clearColorFilter();
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
drawable.invalidateSelf();
Drawable wrapDrawable = DrawableCompat.wrap(drawable).mutate();
DrawableCompat.setTint(wrapDrawable, color);
return wrapDrawable;
}
and call in this manner:
MenuItem location = menu.findItem(R.id.action_location);
DrawableUtils.setTintDrawable(location.getIcon(), Color.WHITE);
Basically, when you set menu, the three-dot icon takes up the color of android:textColorSecondary from the AppTheme, which in default is set to Black.
So if you are not using, textColorSecondary anywhere in your project, then you can simply add the following line
<item name="android:textColorSecondary">#color/White</item>
After adding it may look like this.
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
<!-- Customise your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="android:textColorSecondary">#color/White</item>
</style>
I'm using CheckboxPreference in a PreferenceActivity and an AppCompat theme from the v21 support library. As you already know, with this latest library widgets like checkboxes, editTexts, radio buttons etc are tinted with the secondary color defined in the theme. In the preference screen, text is in the right color as specifified by my theme, but checkboxes and edittext are not. It seems that when the CheckboxPreference instance creates the widget, it doesn't apply my theme to it.
Radio buttons in a normal layout, tinted:
Checkbox from the CheckboxPreference, not tinted:
I'm using as the parent theme Theme.AppCompat.Light.NoActionBar. This happens to every subclass of Preference with a widget, like EditTextPreference to say one, where the EditText has a black bottom line, instead of a tinted line. How can I apply the tint to the widgets shown by the Preference subclasses?
UPDATE: tinting is not applied because PreferenceActivity extends the framework Activity. In the working case, I'm using an ActionBarActivity from the support library. Now the question is: how come?
Edit: As of AppCompat 22.1, any activity can be themed using AppCompatDelegate. The name of the tinted view classes also changed from v7.internal.widget.TintXYZ to v7.widget.AppCompatXYZ. The answer below is for AppCompat 22.0 and older.
I've also came across this problem and solved it by simply copying the code related to widget tinting from ActionBarActivity. One downside of this solution is that it relies on internal classes that might change or become unavailable in the future.
import android.support.v7.internal.widget.TintCheckBox;
import android.support.v7.internal.widget.TintCheckedTextView;
import android.support.v7.internal.widget.TintEditText;
import android.support.v7.internal.widget.TintRadioButton;
import android.support.v7.internal.widget.TintSpinner;
public class MyActivity extends PreferenceActivity {
#Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
// Allow super to try and create a view first
final View result = super.onCreateView(name, context, attrs);
if (result != null) {
return result;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
// If we're running pre-L, we need to 'inject' our tint aware Views in place of the
// standard framework versions
switch (name) {
case "EditText":
return new TintEditText(this, attrs);
case "Spinner":
return new TintSpinner(this, attrs);
case "CheckBox":
return new TintCheckBox(this, attrs);
case "RadioButton":
return new TintRadioButton(this, attrs);
case "CheckedTextView":
return new TintCheckedTextView(this, attrs);
}
}
return null;
}
}
This works because onCreateView gets called by the LayoutInflater service for every view that is being inflated from a layout resource, which allows the activity to override which classes get instantiated. Make sure that the activity theme is set to Theme.AppCompat. (or descendants) in the manifest.
See ActionBarActivity.java and ActionBarActivityDelegateBase.java for the original code.
I know this questions is kinda old but I wanted to leave a solution to overcome this issue you've experienced.
First of all I'd like to say that the PreferenceActivity is a relic of pre-honeycomb times so don't expect Google to tint your Widgets in this really really old Activity subset.
Instead of the PreferenceActivity you should use PreferenceFragments which will be wrapped in an Activity (preferably an ActionbarActivity if you want your Widgets to be tinted).
Following a pretty basic code example how your Settings Activity should look like.
Example
public class MySettings extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
getFragmentManager().beginTransaction()
.replace(R.id.container, new MyPreferenceFragment()).commit();
}
public static class MyPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences_file);
}
}
}
Note: In this example I've used a FrameLayout as my container for the PreferenceFragments
Result:
So as you can see your Widgets will be tinted properly according to the colorAccent you've set.
More about PreferenceFragments on developer.android.com (click).
So far, my own (sad) workaround was to create from scratch my own checkbox drawables, using the colors which the checkbox should have been tinted with in the first place.
In styles.xml:
<?xml version="1.0" encoding="utf-8"?>
<style name="AppThemeBase" parent="Theme.AppCompat.Light.NoActionBar">
...
<!-- edit the checkbox appearance -->
<item name="android:listChoiceIndicatorMultiple">#drawable/my_checkbox</item>
...
</style>
drawable/my_checkbox.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="#drawable/checkbox_on" />
<item android:drawable="#drawable/checkbox_off" />
</selector>
checkbox_on" andcheckbox_off` are the PNG drawables for the selected and unselected states, obviously one for each screen density.
If you mind dimension consistency, the baseline (MDPI) dimension of the drawables should be 32px full asset and 18px optical square.
The solution given by Tamás Szincsák works great but it should be updated, if using appcompat-v7:22.1.1, as follows:
imports should be changed to
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.AppCompatCheckedTextView;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatRadioButton;
import android.support.v7.widget.AppCompatSpinner;
And respectively the switch should be
switch (name) {
case "EditText":
return new AppCompatEditText(this, attrs);
case "Spinner":
return new AppCompatSpinner(this, attrs);
case "CheckBox":
return new AppCompatCheckBox(this, attrs);
case "RadioButton":
return new AppCompatRadioButton(this, attrs);
case "CheckedTextView":
return new AppCompatCheckedTextView(this, attrs);
}
If you are using AppCompat, then use the app compat items in your style.xml file.
For example, use:
<style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="colorPrimary">#color/primary</item>
<item name="colorPrimaryDark">#color/primary_dark</item>
<item name="colorAccent">#color/accent</item>
</style>
NOT (notice "android:"):
<style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="android:colorPrimary">#color/primary</item>
<item name="android:colorPrimaryDark">#color/primary_dark</item>
<item name="android:colorAccent">#color/accent</item>
</style>
This fixed the issue for me.
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).