Example usage for android.text SpannableStringBuilder delete

List of usage examples for android.text SpannableStringBuilder delete

Introduction

In this page you can find the example usage for android.text SpannableStringBuilder delete.

Prototype

public SpannableStringBuilder delete(int start, int end) 

Source Link

Usage

From source file:Main.java

public static CharSequence htmlfrom(CharSequence text) {
    Pattern htmlflag1 = Pattern.compile("<(.*?)>");
    SpannableStringBuilder builder = new SpannableStringBuilder(text);
    Matcher matcher = htmlflag1.matcher(text);
    while (matcher.find()) {
        builder.delete(matcher.start(), matcher.end());
        text = builder;//from  ww  w .  ja  va 2s.co  m
        matcher = htmlflag1.matcher(text);
    }
    Pattern htmlflag2 = Pattern.compile("&(.*?);");
    matcher = htmlflag2.matcher(text);
    while (matcher.find()) {
        builder.delete(matcher.start(), matcher.end());
        text = builder;
        matcher = htmlflag2.matcher(text);
    }

    return builder.toString();

}

From source file:Main.java

/**
 * Given either a Spannable String or a regular String and a token, apply
 * the given CharacterStyle to the span between the tokens, and also remove
 * tokens.//  w  w w  .  j ava2 s  . co m
 * <p/>
 * For example, {@code setSpanBetweenTokens("Hello ##world##!", "##",
 *new ForegroundColorSpan(0xFFFF0000));} will return a CharSequence
 * {@code "Hello world!"} with {@code world} in red.
 *
 * @param text  The text, with the tokens, to adjust.
 * @param token The token string; there should be at least two instances of
 *              token in text.
 * @param cs    The style to apply to the CharSequence. WARNING: You cannot
 *              send the same two instances of this parameter, otherwise the
 *              second call will remove the original span.
 * @return A Spannable CharSequence with the new style applied.
 * @see <a href="http://developer.android.com/reference/android/text/style/CharacterStyle
 * .html">Character Style</a>
 */
public static CharSequence setSpanBetweenTokens(CharSequence text, String token, CharacterStyle... cs) {
    // Start and end refer to the points where the span will apply
    int tokenLen = token.length();
    int start = text.toString().indexOf(token) + tokenLen;
    int end = text.toString().indexOf(token, start);

    if (start > -1 && end > -1) {
        // Copy the spannable string to a mutable spannable string
        SpannableStringBuilder ssb = new SpannableStringBuilder(text);
        for (CharacterStyle c : cs) {
            ssb.setSpan(c, start, end, 0);
        }

        // Delete the tokens before and after the span
        ssb.delete(end, end + tokenLen);
        ssb.delete(start - tokenLen, start);

        text = ssb;
    }

    return text;
}

From source file:Main.java

/**
 * Given a snippet string with matching segments surrounded by curly
 * braces, turn those areas into bold spans, removing the curly braces.
 *///w  w w  .j  av  a2  s .  c  om
public static Spannable buildStyledSnippet(String snippet) {
    final SpannableStringBuilder builder = new SpannableStringBuilder(snippet);

    // Walk through string, inserting bold snippet spans
    int startIndex, endIndex = -1, delta = 0;
    while ((startIndex = snippet.indexOf('{', endIndex)) != -1) {
        endIndex = snippet.indexOf('}', startIndex);

        // Remove braces from both sides
        builder.delete(startIndex - delta, startIndex - delta + 1);
        builder.delete(endIndex - delta - 1, endIndex - delta);

        // Insert bold style
        builder.setSpan(new StyleSpan(Typeface.BOLD), startIndex - delta, endIndex - delta - 1,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        //builder.setSpan(new ForegroundColorSpan(0xff111111),
        //        startIndex - delta, endIndex - delta - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        delta += 2;
    }

    return builder;
}

From source file:Main.java

/**
 * Given a snippet string with matching segments surrounded by curly
 * braces, turn those areas into bold spans, removing the curly braces.
 *//* w  w w.  jav  a  2 s.  com*/
public static Spannable buildStyledSnippet(String snippet) {
    final SpannableStringBuilder builder = new SpannableStringBuilder(snippet);

    // Walk through string, inserting bold snippet spans
    int startIndex = -1, endIndex = -1, delta = 0;
    while ((startIndex = snippet.indexOf('{', endIndex)) != -1) {
        endIndex = snippet.indexOf('}', startIndex);

        // Remove braces from both sides
        builder.delete(startIndex - delta, startIndex - delta + 1);
        builder.delete(endIndex - delta - 1, endIndex - delta);

        // Insert bold style
        builder.setSpan(sBoldSpan, startIndex - delta, endIndex - delta - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        delta += 2;
    }

    return builder;
}

From source file:de.ub0r.android.lib.DonationHelper.java

/**
 * Show "donate" dialog./*  www .  j av  a2s .  c  om*/
 * 
 * @param context
 *            {@link Context}
 * @param title
 *            title
 * @param btnDonate
 *            button text for donate
 * @param btnNoads
 *            button text for "i did a donation"
 * @param messages
 *            messages for dialog body
 */
public static void showDonationDialog(final Activity context, final String title, final String btnDonate,
        final String btnNoads, final String[] messages) {
    final Intent marketIntent = Market.getInstallAppIntent(context, DONATOR_PACKAGE, null);

    String btnTitle = String.format(btnDonate, "Play Store");

    SpannableStringBuilder sb = new SpannableStringBuilder();
    for (String m : messages) {
        sb.append(m);
        sb.append("\n");
    }
    sb.delete(sb.length() - 1, sb.length());
    sb.setSpan(new RelativeSizeSpan(0.75f), 0, sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    AlertDialog.Builder b = new AlertDialog.Builder(context);
    b.setTitle(title);
    b.setMessage(sb);
    b.setCancelable(true);
    b.setPositiveButton(btnTitle, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(final DialogInterface dialog, final int which) {
            try {
                context.startActivity(marketIntent);
            } catch (ActivityNotFoundException e) {
                Log.e(TAG, "activity not found", e);
                Toast.makeText(context, "activity not found", Toast.LENGTH_LONG).show();
            }
        }
    });
    b.setNeutralButton(btnNoads, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(final DialogInterface dialog, final int which) {
            try {
                context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(
                        "http://code.google.com/p/ub0rapps/downloads/list?" + "can=3&q=Product%3DDonator")));
            } catch (ActivityNotFoundException e) {
                Log.e(TAG, "activity not found", e);
                Toast.makeText(context, "activity not found", Toast.LENGTH_LONG).show();
            }
        }
    });
    b.show();
}

From source file:com.google.android.apps.iosched.util.UIUtils.java

/**
 * Given a snippet string with matching segments surrounded by curly
 * braces, turn those areas into bold spans, removing the curly braces.
 *//*from  ww  w. j  a  v  a  2s.  co  m*/
public static Spannable buildStyledSnippet(String snippet) {
    final SpannableStringBuilder builder = new SpannableStringBuilder(snippet);

    // Walk through string, inserting bold snippet spans
    int startIndex = -1, endIndex = -1, delta = 0;
    while ((startIndex = snippet.indexOf('{', endIndex)) != -1) {
        endIndex = snippet.indexOf('}', startIndex);

        // Remove braces from both sides
        builder.delete(startIndex - delta, startIndex - delta + 1);
        builder.delete(endIndex - delta - 1, endIndex - delta);

        // Insert bold style
        builder.setSpan(sBoldSpan, startIndex - delta, endIndex - delta - 1,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        delta += 2;
    }

    return builder;
}

From source file:com.android.screenspeak.formatter.EventSpeechRule.java

/**
 * Returns the text content of a given <code>node</code> by performing a
 * preorder traversal of the tree rooted at that node. </p> Note: Android
 * Java implementation is not compatible with Java 5.0 which provides such a
 * method./*  w  w w  .j  av a 2  s. c om*/
 *
 * @param node The node.
 * @return The text content.
 */
private static String getTextContent(Node node) {
    SpannableStringBuilder builder = sTempBuilder;
    getTextContentRecursive(node, builder);
    String text = builder.toString();
    builder.delete(0, builder.length());
    return text;
}

From source file:com.j_o.android.imdb_client.ui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mediaList = new ArrayList<Media>();
    mediaGrid = (GridView) findViewById(R.id.media_grid_view);
    editTxMediaSearch = (EditText) findViewById(R.id.edit_search_media);

    // Input filter that not allow special characters.
    InputFilter filter = new InputFilter() {
        @Override//from w  w  w .ja v  a 2s  .c o m
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                int dend) {

            if (source instanceof SpannableStringBuilder) {
                SpannableStringBuilder sourceAsSpannableBuilder = (SpannableStringBuilder) source;
                for (int i = end - 1; i >= start; i--) {
                    char currentChar = source.charAt(i);
                    if (!Character.isLetterOrDigit(currentChar) && !Character.isSpaceChar(currentChar)) {
                        sourceAsSpannableBuilder.delete(i, i + 1);
                    }
                }
                return source;
            } else {
                StringBuilder filteredStringBuilder = new StringBuilder();
                for (int i = 0; i < end; i++) {
                    char currentChar = source.charAt(i);
                    if (Character.isLetterOrDigit(currentChar) || Character.isSpaceChar(currentChar)) {
                        filteredStringBuilder.append(currentChar);
                    }
                }
                return filteredStringBuilder.toString();
            }
        }
    };
    editTxMediaSearch.setFilters(new InputFilter[] { filter });

    editTxMediaSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                new AskForMediaAsyncTaks().execute(editTxMediaSearch.getText().toString());
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(editTxMediaSearch.getWindowToken(), 0);
                return true;
            }
            return false;
        }

    });

}

From source file:it.mb.whatshare.PairOutboundActivity.java

private void showPairingLayout() {
    View view = getLayoutInflater().inflate(R.layout.activity_qrcode, null);
    setContentView(view);/*ww w.j a  v a2  s  .c om*/
    String paired = getOutboundPaired();
    if (paired != null) {
        ((TextView) findViewById(R.id.qr_instructions))
                .setText(getString(R.string.new_outbound_instructions, paired));
    }
    inputCode = (EditText) findViewById(R.id.inputCode);

    inputCode.setFilters(new InputFilter[] { new InputFilter() {
        /*
         * (non- Javadoc )
         * 
         * @see android .text. InputFilter # filter( java .lang.
         * CharSequence , int, int, android .text. Spanned , int, int)
         */
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                int dend) {
            if (source instanceof SpannableStringBuilder) {
                SpannableStringBuilder sourceAsSpannableBuilder = (SpannableStringBuilder) source;
                for (int i = end - 1; i >= start; i--) {
                    char currentChar = source.charAt(i);
                    if (!Character.isLetterOrDigit(currentChar)) {
                        sourceAsSpannableBuilder.delete(i, i + 1);
                    }
                }
                return source;
            } else {
                StringBuilder filteredStringBuilder = new StringBuilder();
                for (int i = 0; i < end; i++) {
                    char currentChar = source.charAt(i);
                    if (Character.isLetterOrDigit(currentChar)) {
                        filteredStringBuilder.append(currentChar);
                    }
                }
                return filteredStringBuilder.toString();
            }
        }
    }, new InputFilter.LengthFilter(MAX_SHORTENED_URL_LENGTH) });

    inputCode.setOnEditorActionListener(new OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                onSubmitPressed(null);
                return keepKeyboardVisible;
            }
            return false;
        }
    });

    final ImageView qrWrapper = (ImageView) findViewById(R.id.qr_code);
    qrWrapper.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        private boolean createdQRCode = false;

        @Override
        public void onGlobalLayout() {
            if (!createdQRCode) {
                try {
                    Bitmap qrCode = generateQRCode(generateRandomSeed(),
                            getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT
                                    ? qrWrapper.getHeight()
                                    : qrWrapper.getWidth());
                    if (qrCode != null) {
                        qrWrapper.setImageBitmap(qrCode);
                    }
                    createdQRCode = true;
                } catch (WriterException e) {
                    e.printStackTrace();
                }
            }
        }
    });
}

From source file:com.jecelyin.editor.v2.core.text.TextUtils.java

/**
 * Replace instances of "^1", "^2", etc. in the
 * <code>template</code> CharSequence with the corresponding
 * <code>values</code>.  "^^" is used to produce a single caret in
 * the output.  Only up to 9 replacement values are supported,
 * "^10" will be produce the first replacement value followed by a
 * '0'./* w  w w  .  j  av  a 2  s.  c  o  m*/
 *
 * @param template the input text containing "^1"-style
 * placeholder values.  This object is not modified; a copy is
 * returned.
 *
 * @param values CharSequences substituted into the template.  The
 * first is substituted for "^1", the second for "^2", and so on.
 *
 * @return the new CharSequence produced by doing the replacement
 *
 * @throws IllegalArgumentException if the template requests a
 * value that was not provided, or if more than 9 values are
 * provided.
 */
public static CharSequence expandTemplate(CharSequence template, CharSequence... values) {
    if (values.length > 9) {
        throw new IllegalArgumentException("max of 9 values are supported");
    }

    SpannableStringBuilder ssb = new SpannableStringBuilder(template);

    try {
        int i = 0;
        while (i < ssb.length()) {
            if (ssb.charAt(i) == '^') {
                char next = ssb.charAt(i + 1);
                if (next == '^') {
                    ssb.delete(i + 1, i + 2);
                    ++i;
                    continue;
                } else if (Character.isDigit(next)) {
                    int which = Character.getNumericValue(next) - 1;
                    if (which < 0) {
                        throw new IllegalArgumentException("template requests value ^" + (which + 1));
                    }
                    if (which >= values.length) {
                        throw new IllegalArgumentException("template requests value ^" + (which + 1) + "; only "
                                + values.length + " provided");
                    }
                    ssb.replace(i, i + 2, values[which]);
                    i += values[which].length();
                    continue;
                }
            }
            ++i;
        }
    } catch (IndexOutOfBoundsException ignore) {
        // happens when ^ is the last character in the string.
    }
    return ssb;
}