首页 > 解决方案 > 安卓。SetText 不会更改 Button 的文本

问题描述

我有自定义视图 - 自定义键盘。每个按钮都是MaterialButton。我需要实现shift按钮来更改字母大小写,所以我这样做了

private fun onCaseChanged() {
    buttons.forEach { button ->
        (button as? TextView)?.let {
            val text = it.text.toString()
            it.text = if (isUpperCase)
                text.toUpperCase(Locale.getDefault())
            else
                text.toLowerCase(Locale.getDefault())
        }
    }
}

除了 UI 之外,一切都正常工作 - 按钮上的文本不会改变。当我将按钮更改为TextViews - 一切正常。但不适用于任何类型的Button. 所以现在这对我来说似乎是唯一的方法。

但是我仍然很好奇 - 如果离开MaterialButtons是否有另一种方法可以解决这个问题

标签: androidkotlin

解决方案


尝试android:textAllCaps="false"在您的 XML 文件中的 Button 声明。如果成功,我建议更改主题中的默认按钮样式,以便在您需要时默认为 false。

例子

 <Button
        android:id="@+id/button"

        android:textAllCaps="false"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        />

推荐阅读