以编程方式在 Button 上设置 selectableItemBackground。 Android。科特林

Set programmatically selectableItemBackground on Button. Android. Kotlin

我有这段代码,但它不起作用。

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

button.setBackground(background.resourceId)

Error: Type mismatch; Found: Int; Required: Drawable.

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

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