我有一个Costum内置的EditText类,我想知道是否可以更改EditText的字距,对此我有一个问题,因为它将是一个密码字段,所以它无法使用: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;
}
}
我尝试了这个,但是没有成功。我想知道是否有可能在不弄乱“密码字符串”的情况下增加间距。
最佳答案
我认为做到这一点的最佳(唯一方法)是使用具有所需字距的字体,并将其设置在EditText上。似乎没有办法以编程方式更改字距调整。