如何为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
相关产品推荐
相关产品推荐

