android 如何将元素的背景更改为其他可绘制对象?

rbl8hiat  于 2023-04-28  发布在  Android
关注(0)|答案(2)|浏览(99)

我想制作一个textView,它在数字为正数时变绿色,在数字为负数时变红,在数字为0时不可见。
我已将updateView.setDrawable(@Drawable/add_background)更改为updateView.setDrawable(R.drawable.add_background),现在收到错误'setBackground(android.graphics.drawable.Drawable)' in 'android.view.View' cannot be applied to '(int)'
代码如下:

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);
        updateView.setBackground(R.drawable.add_background);
    }
    if (team1UpdateAmount < 0) {
        updateView.setText("" + team1UpdateAmount);
        updateView.setBackground(R.drawable.sub_background);
    }
nhaq1z21

nhaq1z211#

看看这条线

updateView.setBackgroundResource(R.drawable.sub_background)

这就是在代码中引用资源的方式,@引用用于XML

dgsult0t

dgsult0t2#

在实验中,我找到了答案。
我将getResources().getDrawable(R.drawable.add_background)设置为名为addBackground的变量(与sub相同),并在updateView.setBackground(addBackground)中引用该变量
代码现在看起来像这样:

Drawable addBackground = getResources().getDrawable(R.drawable.add_background);
Drawable subBackground = getResources().getDrawable(R.drawable.sub_background);
TextView updateView = findViewById(R.id.Team1UpdateView);

if (team1UpdateAmount == 0) {updateView.setVisibility(View.INVISIBLE); return;}

        updateView.setVisibility(View.VISIBLE);

        if (team1UpdateAmount > 0) {
            updateView.setText("+" + team1UpdateAmount);
            updateView.setBackground(addBackground);
        }
        if (team1UpdateAmount < 0) {
            updateView.setText("" + team1UpdateAmount);
            updateView.setBackground(subBackground);
        }

相关问题