如何使用自定义字体通过spannable方法设置所选文本的字体样式

时间:2012-01-03 09:43:53

标签: java android android-edittext spannable

我想使用自定义字体将样式设置为EditText中的所选文字。我在编译时遇到错误。 The constructor StyleSpan(Typeface) is undefined

我正在申请下面的代码。

int start=editbox.getSelectionStart();
int end=editbox.getSelectionEnd();
Spannable span=(Spannable)editbox.getText();
StyleSpan f = new StyleSpan( 
                            Typeface.createFromAsset(getAssets(),
                             "fonts/genbkbasr.ttf"));
span.setSpan(f, start,end, 0);

感谢。

2 个答案:

答案 0 :(得分:1)

我写了一个类来解决这个限制。它似乎在有限的测试中工作,但我还没有编写我需要它的应用程序。请注意,它假定自定义字体可用作资产,并进行静态调用以检索应用程序的上下文(访问资源所需的上下文)。更好的方法是将Context传递给构造函数..

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

答案 1 :(得分:-2)

此构造函数的可接受值记录为here:

值应为样式常量,如Typeface.BOLD