Floating Action Button Transparent above 5.0.1 - android

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

Related

BottomNavigation view ripple color effect

I've seen this ripple color effect on Material Calculator app, on the Google Play and now on the BottomNavigation view.
How can I make this color effect starting from touch?
Gif: https://d13yacurqjgara.cloudfront.net/users/72535/screenshots/2673294/bottom_navigation_material_design_by_jardson_almeida.gif
I think it will be easier if you use style:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorControlHighlight">#color/ripple_material_dark</item>
</style>
If you know how to make simple ripple, then here is code to change color of it:
RippleDrawable rippleDrawable = (RippleDrawable)view.getBackground(); // assumes bg is a RippleDrawable
int[][] states = new int[][] { new int[] { android.R.attr.state_enabled} };
int[] colors = new int[] { Color.BLUE }; // sets the ripple color to blue
ColorStateList colorStateList = new ColorStateList(states, colors);
rippleDrawable.setColor(colorStateList);
Both answers do the work but I found a library which simplifies the work when using BottomNavigation:
https://github.com/roughike/BottomBar

How to change Android Button ripple colors while preserving other style properties?

I want to inherit all Button styles from default material design style and preserve background colors and shadows which appear when pressing a button (so called elevation). The only thing I want to change is the color of ripple effect (when you touch a button and then move your finger around).
If I use the following style:
<style name="MyTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:buttonStyle">#style/MyTheme.Button</item>
</style>
<style name="MyTheme.Button" parent="Widget.AppCompat.Button.Colored">
<item name="android:background">#drawable/btn_material</item>
</style>
and drawable/btn_material is:
<ripple android:color="#ffff0000">
<item android:id="#android:id/mask"
android:drawable="#android:color/white" />
</ripple>
then my button loses its background color and elevation shadow.
Is there any way to tell the button to keep the default colors and shadows inherited from parent and only replace the ripple color with the one given? Essentially I'd like to achieve something like android:backgroundRipple property which would change only the ripple leaving everything else intact.
RippleDrawable ripple= (RippleDrawable)view.getBackground();
int[][] attr= new int[][] { new int[] { android.R.attr.state_enabled} };
int[] colors = new int[] { Color.RED }; // sets the ripple color to red
ColorStateList color = new Color(states, colors);
ripple.setColor(color);

Changing EditText bottom line color android [duplicate]

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());
}
}

Toolbar icon tinting on Android

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>

Change "on" color of a Switch

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

Categories

Resources