首页 > 解决方案 > 在 Button 上以编程方式设置 selectableItemBackground。安卓。科特林

问题描述

我有这个代码,但它不工作。

val background = TypedValue()        
context!!.theme.resolveAttribute(android.R.attr.selectableItemBackground, background, true)

button.setBackground(background.resourceId)

错误:类型不匹配;找到:整数;必需:可绘制。

标签: androidbuttonkotlinbackground

解决方案


你必须使用setBackgroundResource(int id). 因为setBackground(Drawable d)接受一个Drawable对象。

val background = TypedValue()        
context!!.theme.resolveAttribute(android.R.attr.selectableItemBackground, background, true)
button.setBackgroundResource(background.resourceId)

推荐阅读