I have defined a font for a EditText and now the EditText hint also shows that font, but i need to use a different font for EditText hint, is there a way to achieve this?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Android EditText hint uses the same font that the EditText has
EditText uses textview_hint
layout to show ErrorPopup
popup message.so try as to set different typeface for Hint as:
LayoutInflater inflater = LayoutInflater.from(<Pass context here>);
TextView hintTextView = (TextView) inflater.inflate(
com.android.internal.R.layout.textview_hint, null);
hintTextView.setTypeface(< Typeface Object>);
EDIT:
Because EdiText
internally show Hint popup using ErrorPopup
.
See following link for more help:
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/widget/Editor.java#Editor.invalidateTextDisplayList%28%29
回答2:
No need to use reflection. You can achieve it by creating your own TypefaceSpan
.
public class CustomTypefaceSpan extends TypefaceSpan
{
private final Typeface mNewType;
public CustomTypefaceSpan(Typeface type)
{
super("");
mNewType = type;
}
public CustomTypefaceSpan(String family, Typeface type)
{
super(family);
mNewType = type;
}
@Override
public void updateDrawState(TextPaint ds)
{
applyCustomTypeFace(ds, mNewType);
}
@Override
public void updateMeasureState(TextPaint paint)
{
applyCustomTypeFace(paint, mNewType);
}
private static void applyCustomTypeFace(Paint paint, Typeface tf)
{
int oldStyle;
Typeface old = paint.getTypeface();
if (old == null)
{
oldStyle = 0;
}
else
{
oldStyle = old.getStyle();
}
int fake = oldStyle & ~tf.getStyle();
if ((fake & Typeface.BOLD) != 0)
{
paint.setFakeBoldText(true);
}
if ((fake & Typeface.ITALIC) != 0)
{
paint.setTextSkewX(-0.25f);
}
paint.setTypeface(tf);
}
}
Use it as:
// set font to EditText itself
Typeface editTextTypeface = Typeface.createFromAsset(getAssets(), "font1.ttf");
EditText editText = (EditText) findViewById(R.id.normalEditText);
editText.setTypeface(editTextTypeface);
// set font to Hint
Typeface hintTypeface = Typeface.createFromAsset(getAssets(), "font2.ttf");
TypefaceSpan typefaceSpan = new CustomTypefaceSpan(hintTypeface);
SpannableString spannableString = new SpannableString("some hint text");
spannableString.setSpan(typefaceSpan, 0, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
editText.setHint(spannableString);