Last active
August 3, 2017 09:51
-
-
Save chiemy/9030f3e89f0a4328b5f043b721475dd0 to your computer and use it in GitHub Desktop.
自定义 Span 工具类,可设置文字颜色、大小、字体、样式,字体间加横向、纵向间距
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CustomSpan { | |
private Context mContext; | |
private SpannableStringBuilder mSpannableString; | |
private int mStart; | |
private int mEnd; | |
public CustomSpan(Context context) { | |
mContext = context; | |
mSpannableString = new SpannableStringBuilder(""); | |
} | |
public CustomSpan size(String text, int px) { | |
setSpan(text, new AbsoluteSizeSpan(px)); | |
return this; | |
} | |
public CustomSpan size(int px) { | |
return size(null, px); | |
} | |
public CustomSpan typeface(String text, Typeface typeface) { | |
setSpan(text, new CustomTypefaceSpan(typeface)); | |
return this; | |
} | |
public CustomSpan typeface(Typeface typeface) { | |
return typeface(null, typeface); | |
} | |
public CustomSpan color(String text, int color) { | |
setSpan(text, new ForegroundColorSpan(color)); | |
return this; | |
} | |
public CustomSpan color(int color) { | |
return color(null, color); | |
} | |
public CustomSpan style(String text, int style) { | |
setSpan(text, new TextAppearanceSpan(mContext, style)); | |
return this; | |
} | |
public CustomSpan style(int style) { | |
return style(null, style); | |
} | |
public CustomSpan paddingBottom(int padding) { | |
setSpan("\n \n", new TextAppearanceSpan(null, 0, padding, null, null)); | |
return this; | |
} | |
public CustomSpan paddingRight(int padding) { | |
setSpan(" ", new TextAppearanceSpan(null, 0, padding, null, null)); | |
return this; | |
} | |
public CustomSpan append(String text) { | |
if (!TextUtils.isEmpty(text)) { | |
mStart = mSpannableString.length(); | |
mEnd = mStart + text.length(); | |
mSpannableString.append(text); | |
} | |
return this; | |
} | |
private void setSpan(String text, Object span) { | |
append(text); | |
setSpan(span); | |
} | |
private void setSpan(Object span) { | |
mSpannableString.setSpan(span, mStart, mEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); | |
} | |
public Spannable getSpannable() { | |
return mSpannableString; | |
} | |
public void applyTo(TextView textView) { | |
textView.setText(mSpannableString); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment