How to programmatically round corners and set random background colors

后端 未结 8 1715
眼角桃花
眼角桃花 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:46

    Copying @cimlman's comment into a top-level answer for more visibility:

    PaintDrawable(Color.CYAN).apply {
      setCornerRadius(24f)
    }
    

    FYI: ShapeDrawable (and its subtype, PaintDrawable) uses default intrinsic width and height of 0. If the drawable does not show up in your usecase, you might have to set the dimensions manually:

    PaintDrawable(Color.CYAN).apply {
      intrinsicWidth = -1
      intrinsicHeight = -1
      setCornerRadius(24f)
    }
    

    -1 is a magic constant which indicates that a Drawable has no intrinsic width and height of its own (Source).

提交回复
热议问题