not*_*tme 146

好吧,我无法弄清楚如何使用可用的类,所以我扩展了TypefaceSpan我自己的一个现在它适用于我.这是我做的:

package de.myproject.text.style;

import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.style.TypefaceSpan;

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不知怎的,这对按钮不起作用.有什么想法吗? (2认同)
  • @notme 我应该向这个构造函数中的字符串变量系列传递什么? CustomTypefaceSpan(String family, Typeface type) {} ??? (2认同)

Ben*_*ell 97

虽然notme基本上是正确的想法,但由于"家庭"变得多余,因此给出的解决方案有点苛刻.它也有点不正确,因为TypefaceSpan是Android知道的特殊跨度之一,并且期望与ParcelableSpan接口有关的某些行为(notme的子类不正确,也不可能实现).

更简单,更准确的解决方案是:

public class CustomTypefaceSpan extends MetricAffectingSpan
{
    private final Typeface typeface;

    public CustomTypefaceSpan(final Typeface typeface)
    {
        this.typeface = typeface;
    }

    @Override
    public void updateDrawState(final TextPaint drawState)
    {
        apply(drawState);
    }

    @Override
    public void updateMeasureState(final TextPaint paint)
    {
        apply(paint);
    }

    private void apply(final Paint paint)
    {
        final Typeface oldTypeface = paint.getTypeface();
        final int oldStyle = oldTypeface != null ? oldTypeface.getStyle() : 0;
        final int fakeStyle = oldStyle & ~typeface.getStyle();

        if ((fakeStyle & Typeface.BOLD) != 0)
        {
            paint.setFakeBoldText(true);
        }

        if ((fakeStyle & Typeface.ITALIC) != 0)
        {
            paint.setTextSkewX(-0.25f);
        }

        paint.setTypeface(typeface);
    }
}
Run Code Online (Sandbox Code Playgroud)


and*_*per 5

在 Android P 上,可以使用您所知道的相同 TypefaceSpan 类,如此处所示

但在旧版本上,您可以使用他们在视频后面显示的内容,我已经在此处写过。