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