【问题标题】:Remove FloatingActionButton border programmatically?以编程方式删除 FloatingActionButton 边框?
【发布时间】:2018-10-11 22:44:30
【问题描述】:

FloatingActionButton 预先配置了 0.5dp 边框,这违反了 Google 自己的 Material 准则。

您可以通过app:borderWidth = 0dp删除 XML 中的边框

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

【问题讨论】:

    标签: android floating-action-button


    【解决方案1】:

    没有干净的方法。

    您可以通过反射来实现,使用以下代码 (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)
    

    【讨论】:

    • 感谢您的回答,我有一个问题:为什么只有将值设置为 0 才有效?
    • 它不起作用,因为如果您只是将该值设置为 0,则新值将被忽略,因为该值已用于生成背景可绘制对象,并且永远不会再次使用,除非您调用 setBackgroundDrawable。
    猜你喜欢
    • 2010-12-08
    • 1970-01-01
    • 2017-07-26
    • 2011-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多