1

I'm trying to get toolbar's textColor using this method:

private int getToolbarTextColor() {

    int toolbarTextColor;
    TypedArray typedArray = getTheme().obtainStyledAttributes(new int[]{R.attr.titleTextColor});

    try {
        toolbarTextColor = typedArray.getColor(0, Color.TRANSPARENT);
    } catch (UnsupportedOperationException e) {
        toolbarTextColor = Color.TRANSPARENT;
    } finally {
        typedArray.recycle();
    }

    return toolbarTextColor;
}

but it returns 0. What is the problem in my code? What attribute should I use? Is there another better way to get it?

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
h.nodehi
  • 1,036
  • 1
  • 17
  • 32

2 Answers2

3

Here is a method that uses reflection for obtaining a Toolbar title TextView's color:

@ColorInt public static int getToolbarTitleTextColor(Toolbar toolbar) {
try {
  Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
  f.setAccessible(true);
  TextView mTitleTextView = (TextView) f.get(toolbar);
  if (mTitleTextView != null) {
    return mTitleTextView.getCurrentTextColor();
  }
} catch (Exception  e) {
  e.printStackTrace();
}

return 0;}
0
val a = TintTypedArray.obtainStyledAttributes(context, null, R.styleable.Toolbar, R.attr.toolbarStyle, 0);

title.setTextColor(a.getColor(R.styleable.Toolbar_titleTextColor, -0x1))
subtitle.setTextColor(a.getColor(R.styleable.Toolbar_titleTextColor, -0x1))

(Kotlin)

frouo
  • 5,087
  • 3
  • 26
  • 29