1

I have a costum built EditText Class, I was wondering if it's possible to change the EditText's Kerning, I have an issue with this, because it will be a password field, so it seams I can't use:

builder.append("\u00A0");

Edit: Here is the code.

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;
    }

}

I tried this, but ofc with no success. I was wondering if it's possible to add the spacing without messing with the "password String".

4

1 回答 1

2

我认为最好的(唯一的?)方法是使用具有所需字距的字体并将其设置在 EditText 上。看起来没有办法以编程方式更改字距。

于 2014-08-05T14:39:01.190 回答