How to set font style of selected text using custo

2020-07-24 06:04发布

问题:

I want to set style to selected text from EditText using custom typeface. I am getting below error at compile time. The constructor StyleSpan(Typeface) is undefined.

Below code I am applying.

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

Thanks.

回答1:

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


回答2:

Accepted values for this constructor are documented here:

Values should be style constants, like Typeface.BOLD.