android为我们是提供了在代码中动态设置 vector 的颜色的方法。
- 这是一个 svg 范例的返回 icon,取名icon_back.xml,可以直接放在drawlable文件夹中
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24"> <path android:pathData="M7.9911,12L15.8761,19.8849C16.3599,20.3688 16.3599,21.1532 15.8761,21.6371C15.3923,22.121 14.6077,22.121 14.1239,21.6371L5.3629,12.8761C4.879,12.3922 4.879,11.6078 5.3629,11.1239L14.1239,2.3629C14.6077,1.879 15.3923,1.879 15.8761,2.3629C16.3599,2.8468 16.3599,3.6312 15.8761,4.1151L7.9911,12Z" android:strokeWidth="1" android:fillColor="#FFFFFF" android:fillType="nonZero" android:strokeColor="#00000000"/></vector><?xml version="1.0" encoding="utf-8"?><androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" app:titleMargins="0dp"></androidx.appcompat.widget.Toolbar>Toolbar toolbar = findViewById(R.id.toolbar);VectorDrawableCompat vectorDrawableCompat = VectorDrawableCompat.create(getResources(), R.drawable.icon_back, null); //设置title笔墨颜色toolbar.setTitleTextColor(ContextCompat.getColor(getApplicationContext(), R.color.black)); //你必要改变的颜色vectorDrawableCompat.setTint(ContextCompat.getColor(getApplicationContext(), R.color.black));toolbar.setNavigationIcon(vectorDrawableCompat);<color name="black">#000000</color>末了,有个小坑,如果在共用控件的 base 类 设置了修改 vector 颜色,你会发现一个页面设置了以后,剩余的几个页面也被设置了,以是碰到这种情况可以加判定条件,满足条件的设置对应的颜色,不满足条件的设置默认颜色(这里默以为白色)
比方:
base 中:
protected void setToolBarColor(int color) { Toolbar toolbar = findViewById(R.id.toolbar); VectorDrawableCompat vectorDrawableCompat = VectorDrawableCompat.create(getResources(), R.drawable.icon_back, null); if (color > 0) { toolbar.setTitleTextColor(ContextCompat.getColor(getApplicationContext(), color)); //你必要改变的颜色 vectorDrawableCompat.setTint(ContextCompat.getColor(getApplicationContext(), color)); } else { vectorDrawableCompat.setTint(ContextCompat.getColor(getApplicationContext(), R.color.white)); } toolbar.setNavigationIcon(vectorDrawableCompat); }调用:
setToolBarColor(R.color.black);//设置玄色大概setToolBarColor(-1); //利用默认值 |