通过自定义textview实现方法如下
public class MTextView extends TextView{ private float spacing = Spacing.NORMAL; private CharSequence originalText = ""; public MTextView(Context context) { super(context); } public MTextView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context, attrs); } public MTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } /* * 通过自定义属性来实现 * */ private void init(Context context, AttributeSet attrs) { TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.LetterSpacingTextView); originalText = array.getString(R.styleable.LetterSpacingTextView_text); setSpacing(array.getFloat(R.styleable.LetterSpacingTextView_textSpacing, 0)); array.recycle(); } public float getSpacing() { return this.spacing; } public void setSpacing(float spacing) { this.spacing = spacing; applySpacing(); } @Override public void setText(CharSequence text, BufferType type) { originalText = text; applySpacing(); } @Override public CharSequence getText() { return originalText; } private void applySpacing() { if (this == null || this.originalText == null) return; StringBuilder builder = new StringBuilder(); for (int i = 0; i < originalText.length(); i++) { builder.append(originalText.charAt(i)); if (i + 1 < originalText.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((spacing + 1) / 10), i, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } super.setText(finalText, BufferType.SPANNABLE); } public class Spacing { public final static float NORMAL = 0; }在values文件夹下对应的attrs文件为
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="LetterSpacingTextView"> <attr name="textSpacing" format="float"/> <attr name="text" format="string"/> </declare-styleable> </resources>在xml文件中的使用
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:zch="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" > <com.xt.cq3000.view.MTextView android:textSize="23sp" zch:text="这是一段很长的文字哦" zch:textSpacing="5" android:background="@drawable/txt_click_selector" android:clickable="true" android:layout_width="140dp" android:layout_height="140dp" android:gravity="center" android:layout_centerInParent="true" android:textColor="#ffffff"/> </RelativeLayout>