android – 如何在onTextChanged()中使用setSpan()来保存onTextChanged()的参数?

我实际上是在尝试进行卡格式化,因为我正在尝试实现谷歌从link开始说的内容

You are not told where the change took place because other afterTextChanged() methods may already have made other changes and invalidated the offsets. But if you need to know here, you can use setSpan(Object, int, int, int) in onTextChanged(CharSequence, int, int, int) to mark your place and then look up from here where the span ended up.

从上面我所理解的是我需要在onTextChanged()中使用setSpan保存[CharSequence s,int start,int before,int count]并以某种方式在afterTextChanged()中检索它们.

问题是,在onTextChanged()中我在哪个对象上调用setSpan(),如何在afterTextChanged()中检索这些保存的值.

最佳答案
所以我想出了这一个.下面是一个准确的例子,可以作为一个起点.

import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.RelativeSizeSpan;

public class AwesomeTextWatcherDeluxe implements TextWatcher {

    private RelativeSizeSpan span;
    private SpannableString spannable;


    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // We can use any span here. I use RelativeSizeSpan with size 1, which makes absolutely nothing.
        // Perhaps there are other spans better suited for it?
        span = new RelativeSizeSpan(1.0f);
        spannable = new SpannableString(s);
        spannable.setSpan(span, start, start + count, Spanned.SPAN_COMPOSING);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        int beginIndex = spannable.getSpanStart(span);
        int endIndex = spannable.getSpanEnd(span);

        // Do your changes here.

        // Cleanup
        spannable.removeSpan(span);
        span = null;
        spannable = null;
    }
}

转载注明原文:android – 如何在onTextChanged()中使用setSpan()来保存onTextChanged()的参数? - 代码日志