0

I'm trying to add a background color to two TextViews in Android studio, one is supposed to be red, and the other one is supposed to be blue. I currently have it set to random.

public void buildGuiByCode( Activity activity, int width, int height,
                                int numberOfPieces ) 
{
        positions = new int[numberOfPieces];
        tvs = new TextView[numberOfPieces];
        colors = new int[tvs.length];
        params = new LayoutParams[tvs.length];
        Random random = new Random( );
        labelHeight = height ;
        labelwidth = width / numberOfPieces;

        for( int i = 0; i < tvs.length; i++ ) {
            tvs[i] = new TextView( activity );
            tvs[i].setGravity( Gravity.CENTER);
            colors[i] = Color.rgb( random.nextInt(255 ),
                    random.nextInt(255 ),   random.nextInt(255 ) );
            tvs[i].setBackgroundColor( colors[i] );
            params[i] = new LayoutParams( labelwidth, height );
            params[i].topMargin = 0;


            params[i].leftMargin = labelwidth * i;
            addView( tvs[i], params[i] );
        }
    }
Johannes
  • 377
  • 1
  • 5
  • 16
Charlie Batista
  • 125
  • 1
  • 2
  • 8

1 Answers1

1

You can use setBackgroundResource for setting up the background color. Here is a snippet.

TextView textView = new TextView(activity);
textView.setBackgroundResource(R.color.red);

Refer to this official doc

Lokesh Pandey
  • 1,739
  • 23
  • 50