How to set font style of selected text using custom typeface through spannable method

一个人想着一个人 提交于 2019-12-04 17:10:14

I wrote a class to work around this limitation. It appeared to work in limited testing, but I haven't yet written the application that I needed it for. Note that it assumes that the custom font is available as an asset, and it makes a static call to retrieve the application's context (which it needs to access the resource). A better approach would be to pass in the Context to the constructor..

import android.content.Context;

public class TypefaceResourceSpan extends MetricAffectingSpan implements ParcelableSpan {

private String resourceName_;
private Typeface tf_;

public TypefaceResourceSpan(String resourceName) {
    super();
    resourceName_=resourceName;
    tf_=createTypeface(resourceName_);
}

public TypefaceResourceSpan(Parcel src) {
    resourceName_ = src.readString();
    tf_=createTypeface(resourceName_);
}

private Typeface createTypeface(String resourceName) {
    Typeface result=null;
    Context c=TikunKorimMain.getAppContext();
    if (c==null) {
        Log.e("TypefaceResourceSpan", "Application context is null!");
    }
    AssetManager am=c.getAssets();
    if (am==null) {
        Log.e("TypefaceResourceSpan", "AssetManager is null!");
    }
    result=Typeface.createFromAsset(am, resourceName);
    return result;
}

public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(resourceName_);
}

@Override
public void updateMeasureState(TextPaint p) {
    Typeface old=p.getTypeface();
    if ( old != null && !old.isBold() && tf_.isBold() ) {
        p.setFakeBoldText(true);
    }
    if ( old != null && !old.isItalic() && tf_.isItalic() ) {
        p.setTextSkewX(-0.25f);
    }
    p.setTypeface(tf_);
}

@Override
public void updateDrawState(TextPaint tp) {
    Typeface old=tp.getTypeface();
    if ( old != null && !old.isBold() && tf_.isBold() ) {
        tp.setFakeBoldText(true);
    }
    if ( old != null && !old.isItalic() && tf_.isItalic() ) {
        tp.setTextSkewX(-0.25f);
    }
    tp.setTypeface(tf_);
}

public int getSpanTypeId() {
    // TODO does this work???!?
    return 123456;
}

public int describeContents() {
    return 0;
}
}
clemp6r

Accepted values for this constructor are documented here:

Values should be style constants, like Typeface.BOLD.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!