This is my solution: An EditText class that draws the suffix behind the text. There are two custom attributes for defining the text of the suffix and the suffix padding (to the left corner of the EditText).
public class EditTextWithSuffix extends EditText {
TextPaint textPaint = new TextPaint();
private String suffix = "";
private float suffixPadding;
public EditTextWithSuffix(Context context) {
super(context);
}
public EditTextWithSuffix(Context context, AttributeSet attrs) {
super(context, attrs);
getAttributes(context, attrs, 0);
}
public EditTextWithSuffix(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
getAttributes(context, attrs, defStyleAttr);
}
@Override
public void onDraw(Canvas c){
super.onDraw(c);
int suffixXPosition = (int) textPaint.measureText(getText().toString()) + getPaddingLeft();
c.drawText(suffix, Math.max(suffixXPosition, suffixPadding), getBaseline(), textPaint);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
textPaint.setColor(getCurrentTextColor());
textPaint.setTextSize(getTextSize());
textPaint.setTextAlign(Paint.Align.LEFT);
}
private void getAttributes(Context context, AttributeSet attrs, int defStyleAttr) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.EditTextWithSuffix, defStyleAttr, 0);
if(a != null) {
suffix = a.getString(R.styleable.EditTextWithSuffix_suffix);
if(suffix == null) {
suffix = "";
}
suffixPadding = a.getDimension(R.styleable.EditTextWithSuffix_suffixPadding, 0);
}
a.recycle();
}
}
here is the attributes definition:
<resources>
<declare-styleable name="EditTextWithSuffix">
<attr name="suffix" format="string|reference" />
<attr name="suffixPadding" format="dimension" />
</declare-styleable>
</resources>
@Override public void onDraw(Canvas c) { super.onDraw(c); int suffixXPosition = (int) textPaint.measureText(getText().toString()) + getPaddingLeft(); if (getText().toString().isEmpty() && !getHint().toString().isEmpty()) { suffixXPosition = (int) textPaint.measureText(getHint().toString()) + getPaddingLeft(); } c.drawText(suffix, Math.max(suffixXPosition, suffixPadding), getBaseline(), textPaint); }
– Prittleprattle