2

我想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);

谢谢。

4

2 回答 2

1

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

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;
}
}
于 2012-05-13T04:30:14.833 回答
-2

此处记录了此构造函数的可接受值

值应该是样式常量,例如Typeface.BOLD.

于 2012-01-03T13:02:06.233 回答