简体   繁体   English

Android Drawable 颜色运行时

[英]Android Drawable color runtime

I am developing an android app.我正在开发一个 android 应用程序。 I have two different text view with different text view as shown in below two images:我有两个不同的文本视图和不同的文本视图,如下图所示:

Text view one:文本视图一:

在此处输入图片说明

Text view Two:文本视图二:

在此处输入图片说明

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?如果我应该创建一个可绘制文件,那么我应该如何以编程方式更改颜色?

try this simple example试试这个简单的例子

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 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM