How to programmatically round corners and set random background colors

后端 未结 8 1695
眼角桃花
眼角桃花 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).

    0 讨论(0)
  • 2020-11-29 18:46

    Here's an example using an extension. This assumes the view has the same width and height.

    Need to use a layout change listener to get the view size. Then you can just call this on a view like this myView.setRoundedBackground(Color.WHITE)

    fun View.setRoundedBackground(@ColorInt color: Int) {
        addOnLayoutChangeListener(object: View.OnLayoutChangeListener {
            override fun onLayoutChange(v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) {
    
                val shape = GradientDrawable()
                shape.cornerRadius = measuredHeight / 2f
                shape.setColor(color)
    
                background = shape
    
                removeOnLayoutChangeListener(this)
            }
        })
    }
    
    0 讨论(0)
提交回复
热议问题