Android 是否以编程方式删除FloatingActionButton边框?

Android 是否以编程方式删除FloatingActionButton边框?,android,floating-action-button,Android,Floating Action Button,FloatingActionButton预先配置了一个0.5dp的边框,这违反了谷歌自己的材料指南 您可以通过app:borderWidth=0dp 有没有办法以编程方式更改此属性?没有干净的方法 您可以使用以下代码(Kotlin)通过反射完成此操作: 感谢您的回答,我有一个问题:为什么只有当我将值设置为0时,此项才起作用?它不起作用,因为如果您仅将该值设置为0,则新值将被忽略,因为该值已用于生成背景绘图,并且将不再使用,除非您调用setBackgroundDrawable。 val butto

FloatingActionButton
预先配置了一个0.5dp的边框,这违反了谷歌自己的材料指南

您可以通过
app:borderWidth=0dp


有没有办法以编程方式更改此属性?

没有干净的方法

您可以使用以下代码(Kotlin)通过反射完成此操作:


感谢您的回答,我有一个问题:为什么只有当我将值设置为0时,此项才起作用?它不起作用,因为如果您仅将该值设置为0,则新值将被忽略,因为该值已用于生成背景绘图,并且将不再使用,除非您调用setBackgroundDrawable。
val button: FloatingActionButton     // your button, initialized someway

// set the field mBorderWidth of your button, it's not enough to do this because this value has already been consumed for drawing the button's background; it shouldn't be necessary, anyway set it...
val fieldBorderWidth = FloatingActionButton::class.java.getDeclaredField("mBorderWidth")
fieldBorderWidth.isAccessible = true
fieldBorderWidth.setInt(button, 0)

// the trick is to call again setBackgroundDrawable (it's already been called inside of the constructor) on the field mImpl of the FloatingActionButton; you can call it with the button's parameters but passing 0 as borderWidth. So obtain the needed button's parameters and call that method
// (since all these fields and methods are private you must set everything as accessible)

// get button's parameters
val fieldBackgroundTint = FloatingActionButton::class.java.getDeclaredField("mBackgroundTint")
fieldBackgroundTint.isAccessible = true
val fieldBackgroundTintValue = fieldBackgroundTint.get(button)
val fieldBackgroundTintMode = FloatingActionButton::class.java.getDeclaredField("mBackgroundTintMode")
fieldBackgroundTintMode.isAccessible = true
val fieldBackgroundTintModeValue = fieldBackgroundTintMode.get(button)
val fieldRippleColor = FloatingActionButton::class.java.getDeclaredField("mRippleColor")
fieldRippleColor.isAccessible = true
val fieldRippleColorValue = fieldRippleColor.get(button)

// get button's mImpl field
val methodGetImpl = FloatingActionButton::class.java.getDeclaredMethod("getImpl")
methodGetImpl.isAccessible = true
val fieldImplValue = methodGetImpl.invoke(button)

// get mImpl's setBackgroundDrawable method and call it
val methodSetBackgroundDrawable = fieldImplValue.javaClass.getDeclaredMethod("setBackgroundDrawable", ColorStateList::class.java, PorterDuff.Mode::class.java, Int::class.java, Int::class.java)
methodSetBackgroundDrawable.isAccessible = true
methodSetBackgroundDrawable.invoke(fieldImplValue, fieldBackgroundTintValue, fieldBackgroundTintModeValue, fieldRippleColorValue, 0)