Android Drawable color runtime

旧城冷巷雨未停 提交于 2021-02-11 12:15:46

问题


I am developing an android app. 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?


回答1:


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

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


来源:https://stackoverflow.com/questions/59617139/android-drawable-color-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!