Nis*_*ara 9 android textview xml-drawable
我们有什么方法可以在Drawable使用中着色TextView吗?DrawableTint仅适用于API级别23及更高级别.
目前我正在使用a Vertical Linear Layout来达到我的要求.
<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>
Run Code Online (Sandbox Code Playgroud)
Android工作室建议我使用Compound Drawble它TextView来实现这一目标.而且我能够实现它,但我找不到Tint可绘制的方法.
<TextView
style="@style/ChoiceIllustratorTextStyle"
android:drawablePadding="4dp"
android:drawableTop="@drawable/ic_account_balance_white_24dp"
android:text="@string/ci_text_university" />
Run Code Online (Sandbox Code Playgroud)
kri*_*son 18
这样做的程序化方法是
Drawable[] drawables = textView.getCompoundDrawables();
if (drawables[0] != null) { // left drawable
drawables[0].setColorFilter(color, Mode.MULTIPLY);
}
Run Code Online (Sandbox Code Playgroud)
这适用于所有API级别.
这是Marshmallow之前设备的最佳选择.
Nis*_*ara 13
这个答案基于@kris larson的建议.
我使用以下方法,它在所有设备上都能正常工作.
setTintedCompoundDrawable一个自定义方法,它采用TextView你想要设置复合drawable的,一个drawable res id&和你选择颜色的res 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);
}
Run Code Online (Sandbox Code Playgroud)
Tint tintDrawable方法如下:
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;
}
Run Code Online (Sandbox Code Playgroud)
从1.1.0-alpha03 [ ref ]版本开始,AndroidX appcompat库在TextView中支持着色。
向appcompat库添加依赖项
dependencies {
implementation "androidx.appcompat:appcompat:1.1.0"
}
Run Code Online (Sandbox Code Playgroud)
然后可以像这样从XML着色TextView中的drawable
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:drawableStartCompat="@drawable/ic_plus"
app:drawableTint="@color/red" />
Run Code Online (Sandbox Code Playgroud)
不要忘记包括
xmlns:app="http://schemas.android.com/apk/res-auto"
Run Code Online (Sandbox Code Playgroud)
并从扩展您的活动AppCompatActivity。
您可以TextViewCompat在这种情况下使用类:
TextViewCompat.setCompoundDrawableTintList(TextView, ColorStateList)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7715 次 |
| 最近记录: |