Skip to content

Instantly share code, notes, and snippets.

@hrules6872
Created March 10, 2015 13:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrules6872/b807918053b99de6edb6 to your computer and use it in GitHub Desktop.
Save hrules6872/b807918053b99de6edb6 to your computer and use it in GitHub Desktop.
Price Tag TextView
import android.text.TextPaint;
import android.text.style.SuperscriptSpan;
public class PriceTagSpan extends SuperscriptSpan {
@Override
public void updateDrawState(TextPaint tp) {
tp.baselineShift += (int) (tp.ascent() * 0.33f);
}
@Override
public void updateMeasureState(TextPaint tp) {
tp.baselineShift += (int) (tp.ascent() * 0.33f);
}
}
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.RelativeSizeSpan;
import android.util.AttributeSet;
import android.widget.TextView;
public class PriceTagTextView extends TextView {
private final static String DEFAULT_CURRENCY_TEXT = "$";
private CharSequence currency;
public PriceTagTextView(Context context) {
this(context, null);
}
public PriceTagTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public PriceTagTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
currency = DEFAULT_CURRENCY_TEXT;
}
public void setCurrency(CharSequence currency) {
this.currency = currency;
}
public CharSequence getCurrency() {
return currency;
}
@Override
public void setText(CharSequence text, BufferType type) {
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text);
if (!isEmpty(text) && !isEmpty(currency)) {
if (text.toString().contains(currency)) {
int currencyFound = 0;
while ((currencyFound = text.toString().indexOf(String.valueOf(currency), currencyFound)) != -1) {
spannableStringBuilder = setSpans(spannableStringBuilder, currencyFound, currency.length());
currencyFound += currency.length();
}
} else {
spannableStringBuilder.append(currency);
spannableStringBuilder = setSpans(spannableStringBuilder, spannableStringBuilder.length() - currency.length(), currency.length());
}
}
super.setText(spannableStringBuilder, type);
}
private SpannableStringBuilder setSpans(SpannableStringBuilder spannableStringBuilder, int start, int length) {
spannableStringBuilder.setSpan(new PriceTagSpan(), start, start + length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableStringBuilder.setSpan(new RelativeSizeSpan(0.5f), start, start + length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableStringBuilder;
}
private boolean isEmpty(CharSequence text) {
return text == null || text.toString().trim().length() == 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment