0

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:

enter image description here

Text view Two:

enter image description here

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?

Harsh Shah
  • 2,162
  • 2
  • 19
  • 39
  • if you will use one drawable and change its color programmatically check [this](https://stackoverflow.com/questions/11376516/change-drawable-color-programmatically) – Mohammed Alaa Jan 06 '20 at 19:05
  • @MohammedAlaa, I tried this but what happens is that when I set it programmatically it wasn't showing the text it was just showing the latest color only. – Harsh Shah Jan 07 '20 at 04:18

1 Answers1

0

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>
Mohammed Alaa
  • 3,140
  • 2
  • 19
  • 21