简体   繁体   中英

Programmatically change Actionbar title color in Gingerbread

I have a requirement to programmatically change the actionbar title text color.

I use the following code to set the color in slightly different ways, depending on SDK version

int textColor = getResources().getColor(android.R.color.white);
    if (Build.VERSION.SDK_INT >= 14) {
        // Version 4+
        int titleId = getResources().getIdentifier("action_bar_title", "id", "android");
        TextView abTitle = (TextView) findViewById(titleId);
        if (abTitle != null) {
            abTitle.setTextColor(textColor);
        }
    } else {
        // Other versions
        TextView abTitle = (TextView) getWindow().findViewById(android.R.id.title);
        if (abTitle != null) {
            abTitle.setTextColor(textColor);
        }
    }

It works fine on devices with SDK value 14 or greater. But, for Gingerbread devices, abTitle is always null so the color doesn't get set.

Does anyony have any suggestions?

your if/else is wrong, It should look like

 int titleId;
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
      titleId = getResources().getIdentifier("action_bar_title", "id", "android");
  } else {
      titleId = R.id.action_bar_title;
  }

and then you should be able to get it directly through findViewById

Have you used the support library?? As Actionbar is not supported below api level 11.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM