SetSpan不在ScrollingActivity Title中工作

时间:2016-08-22 23:53:15

标签: android android-toolbar android-collapsingtoolbarlayout spannablestring

我设法通过以下代码在“正常”活动中更改AppBar标题的字体:

 import { Component, ViewChild, ViewContainerRef, ComponentResolver }  from '@angular/core';

 @Component({
   selector: 'my-test',
   template: `
    Test Component
   `
 })
 export class TestComponent {}

 @Component({
   selector: 'my-app',
   template: `<h3 class="title">Basic Angular 2</h3>
   <div #target></div>
   `
 })
 export class AppComponent {
   @ViewChild('target', {read: ViewContainerRef}) target : ViewContainerRef;

   constructor(private componentResolver: ComponentResolver){
     this.render();
   }

   render = () =>  {
     // include app specific logic to get ComponentType
     //  let cmp = Component(metadata)(type);
     this.componentResolver.resolveComponent(TestComponent).then(factory => {
      let component = this.target.createComponent(factory, 0, null, null);
     });
    }
  }

使用自定义类TypefaceSpan:

setContentView(R.layout.activity_scrolling);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);        

    SpannableString s = new SpannableString("MyTitle");
    s.setSpan(new TypefaceSpan(this, "Britannic_Bold.ttf"), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    setTitle(s);

}

但是,这不适用于滚动活动(由Android Studio创建)

虽然文本按预期更改,但滚动活动的标题不会更改其字体。

我已经尝试了很多,包括为工具栏标题创建一个样式但它似乎不起作用。

我有什么可以监督的吗?

以下是滚动活动的XML部分:

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);
}

1 个答案:

答案 0 :(得分:0)

经过一些试验和错误,我找到了解决方案!

只需获取CollapsedToolbarLayout并调用setCollapsedTitleTypeface(customFont)和setExpandedTitleTypeface(customFont)!

像魅力一样! :)