javaandroiddrawable

How do I change the background of an element to a different drawable?


I want to make a textView that turns green with a positive number, red with a negative number, and goes invisible when 0. I have two separate drawables for each background.

I have changed updateView.setDrawable(@Drawable/add_background) to updateView.setDrawable(R.drawable.add_background), and am now getting the error 'setBackground(android.graphics.drawable.Drawable)' in 'android.view.View' cannot be applied to '(int)'

Here is the code:

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);
    }

Solution

  • check out this line

    updateView.setBackgroundResource(R.drawable.sub_background)
    

    thats how you are referencing to resources in code, referencing by @ is for XMLs