Android Drawable颜色运行时 [英] Android Drawable color runtime
本文介绍了Android Drawable颜色运行时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发一个Android应用程序.我有两个具有不同文本视图的文本视图,如以下两幅图所示:
I am developing an android app. I have two different text view with different text view as shown in below two images:
文本视图一:
文本视图二:
我有一个问题,应该创建两个具有不同颜色的不同可绘制文件,还是创建一个可绘制文件并更改颜色运行时间?
I have a question, should I create two different drawable files with different colors or should I create a single drawable file and change the color runtime?
实现此目标的标准方法是什么?
What's the standard way to achieve this?
如果我应该创建一个可绘制文件,那么应该如何以编程方式更改颜色?
If I should create a single drawable file then how should I change to color programmatically?
推荐答案
尝试这个简单的示例
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tvWelcome = findViewById(R.id.tv_welcome);
TextView tvHello = findViewById(R.id.tv_hello);
recolor(this, tvWelcome, getResources().getColor(R.color.red));
recolor(this, tvHello, getResources().getColor(R.color.green));
}
private void recolor(Context context, TextView textView, @ColorInt int color) {
Drawable unwrappedDrawable = AppCompatResources.getDrawable(context, R.drawable.item_background);
if (unwrappedDrawable != null) {
DrawableCompat.wrap(unwrappedDrawable);
DrawableCompat.setTint(unwrappedDrawable, color);
textView.setBackground(unwrappedDrawable);
}
}
}
item_background.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffffff" />
<corners
android:bottomLeftRadius="7dp"
android:bottomRightRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp" />
</shape>
这篇关于Android Drawable颜色运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文