【问题标题】:Material Button with icon on the right右侧带有图标的材质按钮
【发布时间】:2018-11-20 19:16:54
【问题描述】:

来自 Google 的 new material button 非常好。
根据documentation,我们可以设置一个默认显示在左侧的图标。有谁知道怎么设置在右边?我找不到关于此的任何信息。

【问题讨论】:

  • 似乎不可能。看源码,第669行,总是添加到Start(左)github.com/material-components/material-components-android/blob/…
  • 有趣,我认为这是可能的,因为文档说“默认情况下”。他们不允许在 xml 中进行选择,这很糟糕。但多亏了你,我找到了解决方法。我在我的活动中回忆了这个方法并在右侧设置了图标:TextViewCompat.setCompoundDrawablesRelative(button, null, null, button.icon, null)
  • @BenjaminLedet 我正在尝试在按钮上设置 compunddrawble 以实现相同的目的,但我似乎无法修复它。您能否发布代码或指导我如何制作右侧的图标
  • @Snake 我刚刚做了一个扩展:fun MaterialButton.setRightIcon() { TextViewCompat.setCompoundDrawablesRelative(this, null, null, this.icon, null) } 在视图初始化后我把它称为button.setRightIcon()

标签: android material-design android-button material-components material-components-android


【解决方案1】:

我今天搜索了同样的问题,发现:android:layoutDirection="rtl"。它适用于我的测试项目。

【讨论】:

  • 哇,太棒了,谢谢!好久没见过这么复杂的hack了。
【解决方案2】:

只需使用 app:iconGravity 属性或方法setIconGravity()

需要android的材质组件版本1.1.0

您也可以使用app:iconGravity="end"

也照documentation

如果向此按钮添加了开始对齐的图标,请使用默认 MaterialButton 样式中指定的“.Icon”样式之一的样式。 “.Icon”样式略微调整填充以实现更好的视觉平衡。此样式只能与开始对齐的图标按钮一起使用。如果您的图标是端对齐的,则您不能使用“.Icon”样式,而必须手动调整您的填充,以使视觉调整成为镜像。

【讨论】:

  • 如何在文字上方设置图标?
  • @tejaspatel 你可以使用 app:iconGravity="top"
【解决方案3】:

在版本1.1.0-alpha06

中有一个新的end重力值

【讨论】:

    【解决方案4】:

    解决方案 1

    为每个按钮使用这个扩展方法(kotlin):

    fun MaterialButton.setRightIcon() { 
        TextViewCompat.setCompoundDrawablesRelative(this, null, null, this.icon, null) 
    }
    

    解决方案 2(更好的方法)

    扩展MaterialButton 类以在任何地方使用:

    class RtlMaterialButton(context: Context, attrs: AttributeSet) : MaterialButton(context, attrs) {
    
        override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec)
            updateIcon()
        }
        private fun updateIcon() {
            TextViewCompat.setCompoundDrawablesRelative(this, null, null, icon, null)
        }
    
    }
    

    解决方案 3(在minSDK>=17 工作)

    如果您想为图标使用textStartgravity,您可以为每个按钮使用android:layoutDirection="rtl"

    在您的应用中设置android:supportsRtl="true" AndroidManifest.xml 在您的<Application> 标签中

    【讨论】:

      猜你喜欢
      • 2022-01-11
      • 2020-09-12
      • 1970-01-01
      • 2020-02-06
      • 2020-12-25
      • 2019-04-26
      • 1970-01-01
      • 2015-09-23
      相关资源
      最近更新 更多