我已经在SO和复制粘贴的帮助下为我的自定义EditText
创建了前缀修改。
这里是前缀的特定代码:
private String mPrefix = "";
private Rect mPrefixRect = new Rect();
public OpenSansEditText(Context context, AttributeSet attrs) {
super(context, attrs);
applyCustomFont(context, attrs);
applyPrefix(context, attrs);
}
public OpenSansEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
applyCustomFont(context, attrs);
applyPrefix(context, attrs);
}
private void applyPrefix(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.OpenSansET);
String fontFace;
try {
fontFace = a.getString(R.styleable.OpenSansET_prefix);
} finally {
a.recycle();
}
if (fontFace != null){
mPrefix = fontFace;
} else {
mPrefix = "";
}
}
protected void setmPrefix(String prefix){
this.mPrefix = prefix;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (!mPrefix.equals("")){
getPaint().getTextBounds(mPrefix, 0, mPrefix.length(), mPrefixRect);
mPrefixRect.right += getPaint().measureText(" "); // add some offset
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (!mPrefix.equals("")) {
canvas.drawText(mPrefix, super.getCompoundPaddingLeft(), getBaseline(), getPaint());
}
}
@Override
public int getCompoundPaddingLeft() {
return mPrefix.equals("") ? super.getCompoundPaddingLeft()
: super.getCompoundPaddingLeft() + mPrefixRect.width();
}
基本上它的作用是,如果我从xml或通过代码提供了前缀,它会将该前缀绘制到EditText
的开头。例如:
<com.asta.classes.OpenSansEditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/min"
app:prefix="$"/>
此代码生成:
但问题是,如果我设置textColorHint
,前缀的颜色将与提示的颜色相同,如:
如何将前缀颜色修改为指定颜色?在我的情况下,它是让它有自己的颜色,而不是使用提示颜色。
答案 0 :(得分:1)
更新 onDraw 方法
E.g:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (!mPrefix.equals("")) {
Paint paint = getPaint();
paint.setColor(color);
canvas.drawText(mPrefix, super.getCompoundPaddingLeft(), getBaseline(), paint);
}
}
答案 1 :(得分:1)
试试这些:
Typeface font = Typeface.createFromAsset(getAssets(), "OpenSans_Semibold.ttf");
SpannableStringBuilder builder = new SpannableStringBuilder();
String a = "$" + " ";
SpannableString aSpannable = new SpannableString(a);
aSpannable.setSpan(newForegroundColorSpan(getResources().getColor(R.color.color_yellow)), 0, a.length(), 0);
aSpannable.setSpan(new CustomTypefaceSpan("", font), 0, a.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
builder.append(aSpannable);
String b = "Min";
SpannableString bSpannable = new SpannableString(b);
bSpannable.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_white)), 0, b.length(), 0);
bSpannable.setSpan(new CustomTypefaceSpan("", font), 0, b.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
builder.append(bSpannable);
final EditText textV = new EditText(this);
textV.setHint(builder,textV.BufferType.SPANNABLE)`