How to programmatically round corners and set random background colors

后端 未结 8 1710
眼角桃花
眼角桃花 2020-11-29 17:50

I\'d like to round the corners of a view and also change the color of the view based on the contents at runtime.

TextView v = new TextView(context);
v.setTex         


        
8条回答
  •  半阙折子戏
    2020-11-29 18:30

    Total programmatic approach to set rounded corners and add random background color to a View. I have not tested the code, but you get the idea.

     GradientDrawable shape =  new GradientDrawable();
     shape.setCornerRadius( 8 );
    
     // add some color
     // You can add your random color generator here
     // and set color
     if (i % 2 == 0) {
      shape.setColor(Color.RED);
     } else {
      shape.setColor(Color.BLUE);
     }
    
     // now find your view and add background to it
     View view = (LinearLayout) findViewById( R.id.my_view );
     view.setBackground(shape);
    

    Here we are using gradient drawable so that we can make use of GradientDrawable#setCornerRadius because ShapeDrawable DOES NOT provide any such method.

提交回复
热议问题