You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Toolbar标题文本颜色?调用getTitleTextColor()报错

解决MaterialToolbar无法调用getTitleTextColor()的问题

嘿,这个坑我之前踩过!你遇到的问题是因为MaterialToolbar本身并没有直接提供getTitleTextColor()这个方法——虽然普通的Toolbar有,但Material组件库的实现里,标题的颜色是通过TextAppearance样式来管理的,并没有暴露直接的getter方法。

下面给你几个可靠的解决方案:

方案1:从TextAppearance中解析标题颜色(推荐)

这是最稳定的方法,不管你是在布局里直接设置app:titleTextColor,还是通过主题样式配置的,都能准确获取到颜色:

Kotlin代码示例

val context = bottombarToolbar.context
// 获取标题的TextAppearance资源ID
val textAppearanceRes = bottombarToolbar.titleTextAppearance
val titleColor = if (textAppearanceRes != 0) {
    // 解析TextAppearance中的文字颜色
    val ta = context.obtainStyledAttributes(textAppearanceRes, intArrayOf(android.R.attr.textColor))
    val color = ta.getColor(0, android.graphics.Color.WHITE) // 这里的默认值可以根据你的需求调整
    ta.recycle() // 记得回收TypedArray,避免内存泄漏
    color
} else {
    // 如果没有设置自定义TextAppearance,取主题默认的标题颜色
    val ta = context.obtainStyledAttributes(intArrayOf(android.R.attr.textColorPrimary))
    val color = ta.getColor(0, android.graphics.Color.WHITE)
    ta.recycle()
    color
}

Java代码示例

Context context = bottombarToolbar.getContext();
int textAppearanceRes = bottombarToolbar.getTitleTextAppearance();
int titleColor;

if (textAppearanceRes != 0) {
    TypedArray ta = context.obtainStyledAttributes(textAppearanceRes, new int[]{android.R.attr.textColor});
    titleColor = ta.getColor(0, android.graphics.Color.WHITE);
    ta.recycle();
} else {
    TypedArray ta = context.obtainStyledAttributes(new int[]{android.R.attr.textColorPrimary});
    titleColor = ta.getColor(0, android.graphics.Color.WHITE);
    ta.recycle();
}

方案2:直接获取Toolbar内部的标题TextView(不推荐)

如果你确定MaterialToolbar的内部布局不会变化,可以尝试直接找到标题对应的TextView来获取颜色,但这个方法依赖于组件的内部实现,后续版本可能失效:

Kotlin代码示例

val titleTextView = bottombarToolbar.getChildAt(0) as? TextView
val titleColor = titleTextView?.currentTextColor ?: android.graphics.Color.WHITE

Java代码示例

TextView titleTextView = (TextView) bottombarToolbar.getChildAt(0);
int titleColor = titleTextView != null ? titleTextView.getCurrentTextColor() : android.graphics.Color.WHITE;

补充说明

另外,记得检查你的Material Components库版本,确保使用的是较新的稳定版(比如com.google.android.material:material:1.9.0及以上),避免因为版本过低导致的API兼容问题。

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:09:34