Android Drawable color runtime

问题描述 投票:0回答:1

我正在开发一个Android应用。我有两个具有不同文本视图的文本视图,如以下两个图像所示:

文本视图一:

enter image description here

文本视图二:

enter image description here

我有一个问题,应该创建两个具有不同颜色的不同可绘制文件,还是应该创建一个可绘制文件并更改颜色运行时间?

达到此目的的标准方法是什么?

如果要创建一个可绘制的文件,那么应如何以编程方式更改颜色?

android background-color android-drawable android-background android-text-color
1个回答
0
投票

尝试这个简单的例子

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>
© www.soinside.com 2019 - 2024. All rights reserved.