【问题标题】:How to write a multiline text on a Material button?如何在材质按钮上写多行文本?
【发布时间】:2020-06-22 03:53:41
【问题描述】:

我需要制作一个多行文本材质按钮。 我关注了this问题的答案,但事实证明材料按钮的工作方式不同。

<com.google.android.material.button.MaterialButtonToggleGroup
    android:id="@+id/toggle_parent_child"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginEnd="16dp"
    android:theme="@style/Theme.MaterialComponents"
    android:visibility="gone"
    app:checkedButton="@id/button_parent"
    app:singleSelection="true">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/button_parent"
        style="@style/Login.Button.ToggleButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Parent\n Device" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/button_child"
        style="@style/Login.Button.ToggleButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Child \n Device" />

我明白了:

但我需要像这样将每个单词放在不同的行中:

【问题讨论】:

    标签: android xml user-interface materialbutton


    【解决方案1】:

    可能已经晚了,但这是我修复它的实现

    class MonsterButtonToggleGroup : MaterialButtonToggleGroup {
    
        constructor(context: Context) : super(context)
        constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
        constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
    
    
        override fun addView(child: View?, index: Int, params: ViewGroup.LayoutParams?) {
            super.addView(child, index, params)
            if (child is MaterialButton)
                child.maxLines = 2
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用replace 使其成为您MaterialButton 中的多行字符串,就像这样 -

      val singleLine = getString(R.string.hello_blank_activity)
      demoText.text = singleLine
      
      val multiLine = singleLine.replace(" ", "\n")
      demoTextMulti.text = multiLine
      

      这是输出的截图 -

      【讨论】:

      • 感谢您的回答,但这与将原始文本设置为包含 \n 不一样吗?我还是尝试了您的解决方案,遗憾的是它没有成功。我正在使用 kotlin:val singleLine:String = button_parent.text.toString()val multiLine = singleLine.replace(" ", "\n")button_parent.text = multiLine
      • 啊,明白了。问题不在MaterialButton 中,因为MaterialButtonToggleGroup 而发生。所以,如果我没记错的话,MaterialButtonToggleGroup 不支持多行。它支持单行文本和/或图像。您可以查看LINKMaterial.io
      猜你喜欢
      • 2017-07-29
      • 2013-11-11
      • 2020-10-18
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 2019-03-25
      • 2015-10-03
      相关资源
      最近更新 更多