Price Tag TextView
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
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