如何在Kotlin中调用getBackground.setStroke方法?如何为按钮背景设置描边?
嘿,我来帮你搞定Kotlin里按钮背景描边的问题,顺便解释下为啥你找不到setStroke方法~
在Kotlin中给按钮背景设置描边的正确姿势
你在Java里的代码核心是把按钮背景强转成GradientDrawable再调用描边方法,Kotlin里逻辑完全一致,只是语法和空安全处理需要注意:
推荐写法:安全类型转换(避免空指针)
因为按钮的background有可能为空,或者实际类型不是GradientDrawable,用as?做安全转换,转换失败会返回null,再配合空安全调用,稳妥又安全:
val gradientDrawable = mAllButton.background as? GradientDrawable gradientDrawable?.setStroke(1, ContextCompat.getColor(this, R.color.colorPrimary))
快捷写法:非空断言(谨慎使用)
如果你百分百确定按钮的背景就是GradientDrawable(比如你在布局里给按钮设置的背景就是渐变drawable),可以用as!强转,但如果类型不匹配会直接抛出异常,所以要谨慎:
val gradientDrawable = mAllButton.background as! GradientDrawable gradientDrawable.setStroke(1, ContextCompat.getColor(this, R.color.colorPrimary))
为啥直接在background上找不到setStroke?
这是因为View.background的返回类型是通用的Drawable,而setStroke是GradientDrawable这个子类特有的方法。就像你在Java里必须强制转换一样,Kotlin里也得先把Drawable转换成GradientDrawable,才能调用这个专属方法~
另外,如果你的项目用了AndroidX,且当前类是AppCompatActivity的子类,还可以简化颜色获取的代码:
gradientDrawable?.setStroke(1, getColor(R.color.colorPrimary))
内容的提问来源于stack exchange,提问作者Jay
相关产品推荐
相关产品推荐

