更改字母间距/字距调整EditText

时间:2014-08-05 14:27:07

标签: android android-edittext kerning

我有一个Costum构建的EditText类,我想知道是否可以更改EditText的Kerning,我有一个问题,因为它将是一个密码字段,所以它接缝我无法使用:

builder.append("\u00A0");

编辑:以下是代码。

public class MyEditText extends EditText {
    private float mLetterSpacing = 0;
    private CharSequence mOriginalText = "";

    public MyEditText(Context context) {
        super(context);
    }

    public MyEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    public float getLetterSpacing() {
        return mLetterSpacing;
    }

    public void setLetterSpacing(float letterSpacing) {
        mLetterSpacing = letterSpacing;
        applyLetterSpacing();
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        mOriginalText = text;
        applyLetterSpacing();
    }

    public void applyLetterSpacing() {
        StringBuilder builder = new StringBuilder();
        for(int i = 0; i < mOriginalText.length(); i++) {
            String c = ""+ mOriginalText.charAt(i);
            builder.append(c.toLowerCase());
            if(i+1 < mOriginalText.length()) {
                builder.append("\u00A0");
            }
        }
        SpannableString finalText = new SpannableString(builder.toString());
        if(builder.toString().length() > 1) {
            for(int i = 1; i < builder.toString().length(); i+=2) {
                finalText.setSpan(new ScaleXSpan((mLetterSpacing+1)/10), i, i+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        super.setText(finalText, BufferType.SPANNABLE);
    }

    public static Spannable applyKerning(CharSequence src, float kerning) {
        if (src == null) return null;
        final int srcLength = src.length();
        if (srcLength < 2) return src instanceof Spannable
                ? (Spannable)src
                : new SpannableString(src);

        final String nonBreakingSpace = "\u00A0";
        final SpannableStringBuilder builder = src instanceof SpannableStringBuilder
                ? (SpannableStringBuilder)src
                : new SpannableStringBuilder(src);
        for (int i = src.length() - 1; i >= 1; i--)
        {
            builder.insert(i, nonBreakingSpace);
            builder.setSpan(new ScaleXSpan(kerning), i, i + 1,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        return builder;
    }

}

我试过这个,但是没有成功。我想知道是否可以在不弄乱&#34;密码字符串&#34;的情况下添加间距。

1 个答案:

答案 0 :(得分:2)

我认为最好(仅限?)的方法是使用具有所需字距的字体字体并在EditText上设置它。看起来没有办法以编程方式改变字距调整。