You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Android Toolbar取消全大写,实现仅首字母大写问题求助

解决Toolbar标题仅首字母大写的问题

嘿,我立刻就发现问题根源了——你在自定义toolbar.xml里的标题TextView,自己设置了app:textAllCaps="true",这个属性优先级比主题里的配置高,所以不管你在styles.xml里怎么设,标题都会强制全大写!咱们一步步调整就能实现仅首字母大写的需求:

第一步:关闭TextView的强制全大写

先把toolbar.xml里标题TextView的app:textAllCaps="true"删掉或者改成false,这是最关键的一步:

修改后的TextView代码:

<TextView
    android:id="@+id/toolbaTitleTextView"
    style="@style/textViewOneLine"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center|start"
    android:text="@string/application_name"
    app:textAllCaps="false"
    android:textColor="@android:color/white"
    android:textSize="18sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="@+id/toolBar"
    app:layout_constraintEnd_toEndOf="@+id/toolBar"
    app:layout_constraintTop_toTopOf="@+id/toolBar"
    app:layout_constraintStart_toEndOf="@+id/imageView"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"/>

第二步:实现仅首字母大写

这里给你两种常用方案,按需选择:

方案一:XML属性实现(静态标题适用)

如果你的标题是固定的字符串资源,可以直接在strings.xml里把字符串写成首字母大写的格式,比如:

<string name="application_name">My Awesome App</string>

这种方式最简单,适合标题不会动态变化的场景。

方案二:代码动态处理(动态标题适用)

如果标题需要动态修改,就在Activity里拿到TextView后,手动处理字符串格式:

TextView toolbarTitle = findViewById(R.id.toolbaTitleTextView);
String originalTitle = getString(R.string.application_name);
// 处理成首字母大写,其余小写
String capitalizedTitle = originalTitle.substring(0, 1).toUpperCase() + originalTitle.substring(1).toLowerCase();
toolbarTitle.setText(capitalizedTitle);

要是你希望保留原字符串中每个单词的首字母大写(比如英文短语格式),可以用自定义工具方法:

public static String capitalizeEachWord(String input) {
    if (input == null || input.isEmpty()) return input;
    String[] words = input.split(" ");
    StringBuilder sb = new StringBuilder();
    for (String word : words) {
        if (word.length() > 0) {
            sb.append(Character.toUpperCase(word.charAt(0)))
              .append(word.substring(1).toLowerCase())
              .append(" ");
        }
    }
    return sb.toString().trim();
}

// 调用
toolbarTitle.setText(capitalizeEachWord(originalTitle));

额外说明

你之前在主题里设置的android:textAllCaps="false"和关闭默认Toolbar标题的代码都是没问题的,只是被自定义TextView的属性覆盖了。调整完上面的步骤,标题就会变成你想要的格式啦!

内容的提问来源于stack exchange,提问作者Alexei

火山引擎 最新活动