Java 类android.text.Spannable.Factory 实例源码

项目:Bimoid-IM-Android    文件:MyTextView.java   
public void setText(CharSequence text, boolean detect_links){
    this.text = text;
    if(detect_links){
        Spannable s = null;
        if(this.text instanceof Spannable){
            s = (Spannable)this.text;
        }else{
            s = Factory.getInstance().newSpannable(this.text);
        }
        Linkify.addLinks(s, Linkify.WEB_URLS);
        this.text = s;
    }
    //relayout();
    invalidate();
}
项目:Android-Commons    文件:UI.java   
/**
 * Replaces the given texts with the given image (as a `Spannable`) in the specified `EditText` instance
 *
 * @param context a context reference
 * @param editText the `EditText` instance to operate on
 * @param searchTexts the texts to replace
 * @param replacementImages the resource IDs of the images to insert
 */
public static void replaceTextsWithImages(final Context context, final EditText editText, final String[] searchTexts, final int[] replacementImages) {
    if (searchTexts.length != replacementImages.length) {
        throw new RuntimeException("Number of search texts must match the number of replacement images");
    }

    final int oldCursorPosition = editText.getSelectionStart();
    final Factory spannableFactory = Spannable.Factory.getInstance();
    final Spannable spannable = spannableFactory.newSpannable(editText.getText().toString());

    for (int i = 0; i < searchTexts.length; i++) {
        final Pattern pattern = Pattern.compile(Pattern.quote(searchTexts[i]));
        final Matcher matcher = pattern.matcher(spannable);

        boolean set;
        while (matcher.find()) {
            set = true;
            for (ImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), ImageSpan.class)) {
                if (spannable.getSpanStart(span) >= matcher.start() && spannable.getSpanEnd(span) <= matcher.end()) {
                    spannable.removeSpan(span);
                }
                else {
                    set = false;
                    break;
                }
            }

            if (set) {
                spannable.setSpan(new ImageSpan(context, replacementImages[i]), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
    }

    editText.setText(spannable);

    if (oldCursorPosition >= 0) {
        editText.setSelection(oldCursorPosition);
    }
}