如何通过Kotlin中的代码使TextView圆角边框

时间:2018-12-16 10:14:54

标签: android android-studio kotlin

我通过代码创建了textView 我想用其他颜色的边框制作弯曲的边缘,但我不知道 这段代码TextView

val name_label1 =TextView(this)
  Layout.addView(name_label1)
  name_label1!!.layoutParams.height = 200.toInt()
  name_label1!!.layoutParams.width = 200.toInt()
  name_label1!!.x = 30.toFloat()
  name_label1!!.y = 30.toFloat()
  name_label1.text = "Hello"
  name_label1.textSize = 20.toFloat()
  name_label1.setTextColor(Color.WHITE)
  name_label1.setBackgroundColor(Color.BLUE)
  name_label1.setTypeface(null,Typeface.BOLD)
  name_label1.gravity = Gravity.CENTER

1 个答案:

答案 0 :(得分:0)

科特林的圆角

定义形状(作为函数):

@SuppressLint("ResourceAsColor")
fun customBg() = GradientDrawable().apply {
shape = GradientDrawable.RECTANGLE
cornerRadius = 10f
setStroke(4, ContextCompat.getColor(applicationContext, 
R.color.colorPrimaryDark))
}

在任何TextView上使用它

txtView.background = customBg()

扩展功能的力量:

TextView上的扩展名

fun TextView.customBg() {
background = GradientDrawable().apply {
    shape = GradientDrawable.RECTANGLE
    cornerRadius = 40f
    setStroke(
        4, ContextCompat.getColor(context, R.color.colorPrimaryDark)
    )
}
}

用作

txtView.customBg()

Rounded Corners