You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为TextView按数值设置不同背景Drawable?解决参数类型错误

解决TextView设置背景资源的类型不匹配错误

你遇到的错误是因为setBackground()方法需要传入Drawable对象,但你传入的是资源ID(int类型),类型不兼容导致的。

有两种简单的解决办法:

方法一:用专门的背景资源设置方法

直接调用setBackgroundResource(),这个方法可以直接接收资源ID参数,代码修改如下:

Integer team1UpdateAmount = 0;

TextView updateView = findViewById(R.id.team1UpdateView);
if (team1UpdateAmount == 0) {
    updateView.setVisibility(View.INVISIBLE); 
    return;
}

updateView.setVisibility(View.VISIBLE);

if (team1UpdateAmount > 0) {
    updateView.setText("+" + team1UpdateAmount);
    // 替换成setBackgroundResource
    updateView.setBackgroundResource(R.drawable.add_background);
}
if (team1UpdateAmount < 0) {
    updateView.setText("" + team1UpdateAmount);
    // 同样替换
    updateView.setBackgroundResource(R.drawable.sub_background);
}

方法二:将资源ID转为Drawable对象再传入

如果一定要用setBackground(),可以通过ContextCompat.getDrawable()把资源ID转换成Drawable对象:

// 正数情况
updateView.setBackground(ContextCompat.getDrawable(this, R.drawable.add_background));
// 负数情况
updateView.setBackground(ContextCompat.getDrawable(this, R.drawable.sub_background));

注意这里的this要换成当前的Context(比如Activity实例)。

推荐用方法一,代码更简洁直接,完全适配你的需求。

内容的提问来源于stack exchange,提问作者Speedy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 15:52:36