在TextView中设置字母之间的间距

8

有没有办法在editText中设置字母之间的自定义间距(以像素为单位)?我只找到了如何设置行之间的间距,但是没有找到在同一行上字母之间的间距。


看这里:https://dev59.com/DnNA5IYBdhLWcg3wL6oc - novalagung
这不是关于IOS或Objective C的问题,我需要在Android上实现它,正如您在问题标签中所看到的。 - Buda Gavril
抱歉,我没有看到那个。 - novalagung
4个回答

12

使用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" />

相关方法:

setLetterSpacing(float)


此功能仅适用于API级别+21。 - Maher Abuthraa

2

今天我自己解决了这个问题,以下是一些关于此问题的更新:

从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());
    }
}

0

我已经使用过这个,如果不是所有的API级别,那么它适用于大多数API级别。

KerningViews

提供了一组视图,允许调整该视图中字符之间的间距,也就是所谓的字距效果(Kerning effect)。

https://github.com/aritraroy/KerningViews


0

您可以实现一个自定义的TextWatcher,并在用户输入1时添加X个空格。


请原谅我的直言,但这个解决方案很糟糕,虽然能用但是很糟糕。 - ademar111190
我同意,那只是我随口说的回答,你会怎样实现这个? - robisaks

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接