【发布时间】:2018-10-11 22:44:30
【问题描述】:
FloatingActionButton 预先配置了 0.5dp 边框,这违反了 Google 自己的 Material 准则。
您可以通过app:borderWidth = 0dp删除 XML 中的边框
有没有办法以编程方式更改此属性?
【问题讨论】:
标签: android floating-action-button
FloatingActionButton 预先配置了 0.5dp 边框,这违反了 Google 自己的 Material 准则。
您可以通过app:borderWidth = 0dp删除 XML 中的边框
有没有办法以编程方式更改此属性?
【问题讨论】:
标签: android floating-action-button
没有干净的方法。
您可以通过反射来实现,使用以下代码 (Kotlin):
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)
【讨论】: