Like me , I guess many of us want to show a different size and styled text in action bar. If you are using ToolBar its fairly easy but for all those old projects that still have Android’s action bar its a pretty hard work. But you can achieve this with the help of CustomView. Yes you can add a CustomView to your action bar. Apply your style on this custom view and add it to the action bar.
So lets create an example, here I want my Action bar title with center gravity and textSize of 15sp.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
ActionBar bar = getSupportActionBar(); if(bar!=null){ TextView tv = new TextView(getApplicationContext()); LayoutParams lp = new RelativeLayout.LayoutParams( LayoutParams.MATCH_PARENT, // Width of TextView LayoutParams.WRAP_CONTENT); // Height of TextView tv.setLayoutParams(lp); tv.setText(bar.getTitle()); tv.setGravity(Gravity.CENTER); tv.setTextColor(Color.WHITE); tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15); bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); bar.setCustomView(tv); } } |
And its done. But be careful as after this non of your setTitle() function will change the Title of your activity.