Android examples for java.lang:Character
Create spannable from text that includes some CharSequence.
/*/*from ww w . ja v a 2 s . c o m*/ * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.text.Spannable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; import android.util.Log; import java.util.List; public class Main{ /** * Create spannable from text that includes some CharSequence. If the CharSequence has any spans * they would be copied to result spannable * @param text - some text that potentially contains CharSequence template * @param innerTemplate - CharSequence that is supposed but not necessary to be Spanned. * If it is Spanned the spans are copied to result Spannable * @return Spannable object that contains incoming text and spans from innerTemplate */ public static Spannable createSpannableFromTextWithTemplate( String text, CharSequence innerTemplate) { SpannableString result = new SpannableString(text); if (innerTemplate instanceof Spanned) { int index = text.indexOf(innerTemplate.toString()); if (index >= 0) { copySpans(result, (Spanned) innerTemplate, index); } } return result; } /** * Utility that copies spans from fromSpan to toSpan * @param toSpan - Spannable that is supposed to contain fromSpan. * @param fromSpan - Spannable that could contain spans that would be copied to toSpan * @param startIndex - Starting index of occurrence fromSpan in toSpan */ private static void copySpans(Spannable toSpan, Spanned fromSpan, int startIndex) { if (startIndex < 0 || startIndex >= toSpan.length()) { LogUtils.log( StringBuilderUtils.class, Log.ERROR, "startIndex parameter (" + startIndex + ") is out of toSpan length " + toSpan.length()); return; } Object[] spans = fromSpan.getSpans(0, fromSpan.length(), Object.class); if (spans != null && spans.length > 0) { for (Object span : spans) { int spanStartIndex = fromSpan.getSpanStart(span); int spanEndIndex = fromSpan.getSpanEnd(span); if (spanStartIndex >= spanEndIndex) { continue; } int spanFlags = fromSpan.getSpanFlags(span); toSpan.setSpan(span, startIndex + spanStartIndex, startIndex + spanEndIndex, spanFlags); } } } }