How to Set a Custom Font in the ActionBar Title?

后端 未结 17 1515
面向向阳花
面向向阳花 2020-11-22 09:46

How (if possible) could I set a custom font in a ActionBar title text(only - not the tab text) with a font in my assets folder? I don\'t want to use the android:logo option.

相关标签:
17条回答
  • 2020-11-22 09:58

    I agree that this isn't completely supported, but here's what I did. You can use a custom view for your action bar (it will display between your icon and your action items). I'm using a custom view and I have the native title disabled. All of my activities inherit from a single activity, which has this code in onCreate:

    this.getActionBar().setDisplayShowCustomEnabled(true);
    this.getActionBar().setDisplayShowTitleEnabled(false);
    
    LayoutInflater inflator = LayoutInflater.from(this);
    View v = inflator.inflate(R.layout.titleview, null);
    
    //if you need to customize anything else about the text, do it here.
    //I'm using a custom TextView with a custom font in my layout xml so all I need to do is set title
    ((TextView)v.findViewById(R.id.title)).setText(this.getTitle());
    
    //assign the view to the actionbar
    this.getActionBar().setCustomView(v);
    

    And my layout xml (R.layout.titleview in the code above) looks like this:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent" >
    
    <com.your.package.CustomTextView
            android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="10dp"
                android:textSize="20dp"
                android:maxLines="1"
                android:ellipsize="end"
                android:text="" />
    </RelativeLayout>
    
    0 讨论(0)
  • 2020-11-22 09:58
    int titleId = getResources().getIdentifier("action_bar_title", "id",
                "android");
        TextView yourTextView = (TextView) findViewById(titleId);
        yourTextView.setTextColor(getResources().getColor(R.color.black));
        yourTextView.setTypeface(face);
    
    0 讨论(0)
  • 2020-11-22 09:59

    You can do this using a custom TypefaceSpan class. It's superior to the customView approach indicated above because it doesn't break when using other Action Bar elements like expanding action views.

    The use of such a class would look something like this:

    SpannableString s = new SpannableString("My Title");
    s.setSpan(new TypefaceSpan(this, "MyTypeface.otf"), 0, s.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    
    // Update the action bar title with the TypefaceSpan instance
    ActionBar actionBar = getActionBar();
    actionBar.setTitle(s);
    

    The custom TypefaceSpan class is passed your Activity context and the name of a typeface in your assets/fonts directory. It loads the file and caches a new Typeface instance in memory. The complete implementation of TypefaceSpan is surprisingly simple:

    /**
     * Style a {@link Spannable} with a custom {@link Typeface}.
     * 
     * @author Tristan Waddington
     */
    public class TypefaceSpan extends MetricAffectingSpan {
          /** An <code>LruCache</code> for previously loaded typefaces. */
        private static LruCache<String, Typeface> sTypefaceCache =
                new LruCache<String, Typeface>(12);
    
        private Typeface mTypeface;
    
        /**
         * Load the {@link Typeface} and apply to a {@link Spannable}.
         */
        public TypefaceSpan(Context context, String typefaceName) {
            mTypeface = sTypefaceCache.get(typefaceName);
    
            if (mTypeface == null) {
                mTypeface = Typeface.createFromAsset(context.getApplicationContext()
                        .getAssets(), String.format("fonts/%s", typefaceName));
    
                // Cache the loaded Typeface
                sTypefaceCache.put(typefaceName, mTypeface);
            }
        }
    
        @Override
        public void updateMeasureState(TextPaint p) {
            p.setTypeface(mTypeface);
    
            // Note: This flag is required for proper typeface rendering
            p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
        }
    
        @Override
        public void updateDrawState(TextPaint tp) {
            tp.setTypeface(mTypeface);
    
            // Note: This flag is required for proper typeface rendering
            tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
        }
    }
    

    Simply copy the above class into your project and implement it in your activity's onCreate method as shown above.

    0 讨论(0)
  • 2020-11-22 09:59

    I just did the following inside the onCreate() function:

    TypefaceSpan typefaceSpan = new TypefaceSpan("font_to_be_used");
    SpannableString str = new SpannableString("toolbar_text");
    str.setSpan(typefaceSpan,0, str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    getSupportActionBar().setTitle(str);
    

    I am using the Support Libraries, if you are not using them I guess you should switch to getActionBar() instead of getSupportActionBar().

    In Android Studio 3 you can add custom fonts following this instructions https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html and then use your newly added font in "font_to_be_used"

    0 讨论(0)
  • 2020-11-22 10:02

    use new toolbar in support library design your actionbar as your own or use below code

    Inflating Textview is not an good option try Spannable String builder

    Typeface font2 = Typeface.createFromAsset(getAssets(), "fonts/<your font in assets folder>");   
    SpannableStringBuilder SS = new SpannableStringBuilder("MY Actionbar Tittle");
    SS.setSpan (new CustomTypefaceSpan("", font2), 0, SS.length(),Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
    actionBar.setTitle(ss);
    

    copy below class

    public class CustomTypefaceSpan extends TypefaceSpan{
    
        private final Typeface newType;
    
        public CustomTypefaceSpan(String family, Typeface type) {
            super(family);
            newType = type;
        }
    
        @Override
        public void updateDrawState(TextPaint ds) {
            applyCustomTypeFace(ds, newType);
        }
    
        @Override
        public void updateMeasureState(TextPaint paint) {
            applyCustomTypeFace(paint, newType);
        }
    
        private static void applyCustomTypeFace(Paint paint, Typeface tf) {
            int oldStyle;
            Typeface old = paint.getTypeface();
            if (old == null) {
                oldStyle = 0;
            } else {
                oldStyle = old.getStyle();
            }
    
            int fake = oldStyle & ~tf.getStyle();
            if ((fake & Typeface.BOLD) != 0) {
                paint.setFakeBoldText(true);
            }
    
            if ((fake & Typeface.ITALIC) != 0) {
                paint.setTextSkewX(-0.25f);
            }
    
            paint.setTypeface(tf);
        }
    
    }
    
    0 讨论(0)
  • 2020-11-22 10:07

    Following code will work for all the versions. I did checked this in a device with gingerbread as well as on JellyBean device

     private void actionBarIdForAll()
        {
            int titleId = 0;
    
            if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
            {
                titleId = getResources().getIdentifier("action_bar_title", "id", "android");
            }
            else
            {
              // This is the id is from your app's generated R class when ActionBarActivity is used for SupportActionBar
    
                titleId = R.id.action_bar_title;
            }
    
            if(titleId>0)
            {
                // Do whatever you want ? It will work for all the versions.
    
                // 1. Customize your fonts
                // 2. Infact, customize your whole title TextView
    
                TextView titleView = (TextView)findViewById(titleId);
                titleView.setText("RedoApp");
                titleView.setTextColor(Color.CYAN);
            }
        }
    
    0 讨论(0)
提交回复
热议问题