v23之前版本设备上的Android TextView DrawableTint
我们有没有办法给v23之前版本设备上的Android TextView DrawableTint,android,textview,xml-drawable,Android,Textview,Xml Drawable,我们有没有办法给文本视图中使用的可绘制的上色DrawableTint仅适用于API级别23及以上的产品 目前我正在使用垂直线性布局来实现我的要求 <LinearLayout style="@style/ChoiceIllustratorIconTextContainerStyle"> <ImageView style="@style/ChoiceIllustratorImageStyle" android:contentDescription="@stri
文本视图中使用的可绘制的上色<代码>DrawableTint
仅适用于API级别23及以上的产品
目前我正在使用垂直线性布局
来实现我的要求
<LinearLayout style="@style/ChoiceIllustratorIconTextContainerStyle">
<ImageView
style="@style/ChoiceIllustratorImageStyle"
android:contentDescription="@string/cd_university"
android:src="@drawable/ic_account_balance_white_24dp" />
<TextView
style="@style/ChoiceIllustratorTextStyle"
android:text="@string/ci_text_university" />
</LinearLayout>
实现这一点的编程方法是
Drawable[] drawables = textView.getCompoundDrawables();
if (drawables[0] != null) { // left drawable
drawables[0].setColorFilter(color, Mode.MULTIPLY);
}
这适用于所有API级别
这是您使用棉花糖前设备的最佳选择。此答案基于@kris larson的建议
我使用以下方法,在所有设备上都可以正常工作
setTintedCompoundDrawable
一种自定义方法,它采用TextView
来设置复合可绘制、可绘制的分辨率id和颜色选择的分辨率id
private void setTintedCompoundDrawable(TextView textView, int drawableRes, int tintRes) {
textView.setCompoundDrawablesWithIntrinsicBounds(
null, // Left
Utils.tintDrawable(ContextCompat.getDrawable(getContext(), drawableRes),
ContextCompat.getColor(getContext(), tintRes)), // Top
null, // Right
null); //Bottom
// if you need any space between the icon and text.
textView.setCompoundDrawablePadding(12);
}
TinttintDrawable
方法如下:
public static Drawable tintDrawable(Drawable drawable, int tint) {
drawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(drawable, tint);
DrawableCompat.setTintMode(drawable, PorterDuff.Mode.SRC_ATOP);
return drawable;
}
自版本1.1.0-alpha03[]以来,AndroidX appcompat库支持在TextView中着色
将依赖项添加到appcompat库
dependencies {
implementation "androidx.appcompat:appcompat:1.1.0"
}
然后,TextView中的drawable可以从XML中着色,如下所示
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:drawableStartCompat="@drawable/ic_plus"
app:drawableTint="@color/red" />
要从AppCompatActivity
扩展您的活动,您可以在本例中使用TextViewCompat
类:
TextViewCompat.setCompoundDrawableTintList(TextView, ColorStateList)
这有帮助吗:我查过了,对我的情况没有帮助。谢谢,如果您需要在另一个屏幕上使用不同的颜色或不同的视图状态,我相信您会希望mutate()
可绘制的before调用setColorFilter.PorterDuff.Mode.MULTIPLY不适合我。相反,PorterDuff.Mode.SRC_对我有用。PorterDuff.Mode.MULTIPLY适合您吗?SRC_top是OP决定的,所以它也适合您也就不足为奇了。我记不清了,但我想我可能使用了一个全白色像素的绘图工具,这样乘法和SRC_看起来就差不多了。OP使用兼容类的方法也是一个更好的选择。仅供参考:可绘制[0]左侧、可绘制[1]顶部、可绘制[2]右侧、可绘制[3]底部。谢谢,这很有效。另请注意,如果您在应用程序中的其他位置使用具有不同色调的可绘制资源,则在从资源id加载的可绘制资源上使用getCompoundDrawablesRelative for Start/Top/End/Bottomcall mutate(),以获取单独的可绘制资源。他们应将其添加到ctrl+space快捷方式中
xmlns:app="http://schemas.android.com/apk/res-auto"
TextViewCompat.setCompoundDrawableTintList(TextView, ColorStateList)