android.text.Spannable.Factory Java Examples

The following examples show how to use android.text.Spannable.Factory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: Android-Commons   Author: delight-im   File: UI.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
	}
}