Android EditText提示使用与EditText相同的字体

时间:2016-01-15 06:08:56

标签: java android android-layout android-xml

我已经为EditText定义了一个字体,现在EditText提示也显示了该字体,但是我需要为EditText提示使用不同的字体,有没有办法实现这个?

2 个答案:

答案 0 :(得分:1)

  

Android EditText提示使用与EditText相同的字体

EditText使用textview_hint布局来显示ErrorPopup弹出消息。所以尝试为提示设置不同的字体:

 LayoutInflater inflater = LayoutInflater.from(<Pass context here>);
 TextView hintTextView = (TextView) inflater.inflate(
                        com.android.internal.R.layout.textview_hint, null);
 hintTextView.setTypeface(< Typeface Object>);

修改 因为EdiText在内部使用ErrorPopup显示提示弹出窗口。

请参阅以下链接以获取更多帮助:

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

答案 1 :(得分:0)

无需使用反射。您可以通过创建自己的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);
    }
}

将其用作:

// 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);