简体   繁体   中英

Android Drawable color runtime

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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