有没有办法在editText中设置字母之间的自定义间距(以像素为单位)?我只找到了如何设置行之间的间距,但是没有找到在同一行上字母之间的间距。
有没有办法在editText中设置字母之间的自定义间距(以像素为单位)?我只找到了如何设置行之间的间距,但是没有找到在同一行上字母之间的间距。
使用android:letterSpacing
,我能够在TextView中的字符之间添加间距
<android.support.v7.widget.AppCompatTextView
android:id="@+id/textViewValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:letterSpacing="0.35"
android:maxLines="1" />
相关方法:
今天我自己解决了这个问题,以下是一些关于此问题的更新:
从API 21开始,您可以使用XML属性 android:letterSpacing="2"
或者在代码中使用 myEditText.setLetterSpacing(2);
在API 21之前,使用以下代码的TextWatcher
private static final String LETTER_SPACING = " ";
private EditText myEditText;
private String myPreviousText;
...
// Get the views
myEditText = (EditText) v.findViewById(R.id.edt_code);
myEditText.addTextChangedListener(this);
...
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Nothing here
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Nothing here
}
@Override
public void afterTextChanged(Editable s) {
String text = s.toString();
// Only update the EditText when the user modify it -> Otherwise it will be triggered when adding spaces
if (!text.equals(myPreviousText)) {
// Remove spaces
text = text.replace(" ", "");
// Add space between each character
StringBuilder newText = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
if (i == text.length() - 1) {
// Do not add a space after the last character -> Allow user to delete last character
newText.append(Character.toUpperCase(text.charAt(text.length() - 1)));
}
else {
newText.append(Character.toUpperCase(text.charAt(i)) + LETTER_SPACING);
}
}
myPreviousText = newText.toString();
// Update the text with spaces and place the cursor at the end
myEditText.setText(newText);
myEditText.setSelection(newText.length());
}
}
我已经使用过这个,如果不是所有的API级别,那么它适用于大多数API级别。
KerningViews
提供了一组视图,允许调整该视图中字符之间的间距,也就是所谓的字距效果(Kerning effect)。
您可以实现一个自定义的TextWatcher,并在用户输入1时添加X个空格。