简体   繁体   中英

Add background color to TextView in Android studio

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM