Example usage for android.text SpannedString SpannedString

List of usage examples for android.text SpannedString SpannedString

Introduction

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

Prototype

public SpannedString(CharSequence source) 

Source Link

Document

For the backward compatibility reasons, this constructor copies all spans including android.text.NoCopySpan .

Usage

From source file:Main.java

/**
 * Returns a CharSequence concatenating the specified CharSequences using the specified delimiter,
 * retaining their spans if any.//w  ww. ja  v a 2  s .  c  om
 * 
 * This is mostly borrowed from TextUtils.concat();
 */
public static CharSequence joinSpannables(String delimiter, CharSequence... text) {
    if (text.length == 0) {
        return "";
    }

    if (text.length == 1) {
        return text[0];
    }

    boolean spanned = false;
    for (int i = 0; i < text.length; i++) {
        if (text[i] instanceof Spanned) {
            spanned = true;
            break;
        }
    }

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < text.length; i++) {
        if (i > 0) {
            sb.append(delimiter);
        }
        sb.append(text[i]);
    }

    if (!spanned) {
        return sb.toString();
    }

    SpannableString ss = new SpannableString(sb);
    int off = 0;
    for (int i = 0; i < text.length; i++) {
        int len = text[i].length();

        if (text[i] instanceof Spanned) {
            TextUtils.copySpansFrom((Spanned) text[i], 0, len, Object.class, ss, off);
        }

        off += len + delimiter.length();
    }

    return new SpannedString(ss);
}

From source file:com.gelakinetic.mtgfam.helpers.ImageGetterHelper.java

/**
 * Jellybean had a weird bug, and this fixes it. Silly google!
 * https://code.google.com/p/android/issues/detail?id=35466#c2
 *
 * @param source      The string to add glyphs to
 * @param imageGetter the custom imageGetter, returned by GlyphGetter
 * @return the Spanned with shiny new glyphs
 */// w ww  . j  a v  a 2s.  c om
public static Spanned formatStringWithGlyphs(String source, ImageGetter imageGetter) {
    /* Make sure we're not formatting a null string */
    if (source == null) {
        return new SpannedString("");
    }
    source = source.replace("{", "<img src=\"").replace("}", "\"/>");
    if (Build.VERSION.SDK_INT == 16) {
        source = source.replace("<", " <").replace(">", " >").replace("  ", " ");
    }
    return Html.fromHtml(source, imageGetter, null);
}

From source file:com.gelakinetic.mtgfam.helpers.ImageGetterHelper.java

/**
 * Same weird bug as above, but without the custom imageGetter / tagHandler
 *
 * @param source A string of HTML// ww w  .ja v  a  2s  . c o m
 * @return a formatted Spanned which JellyBean is happy with
 */
public static Spanned formatHtmlString(String source) {
    /* Make sure we're not formatting a null string */
    if (source == null) {
        return new SpannedString("");
    }
    if (Build.VERSION.SDK_INT == 16) {
        source = source.replace("<", " <").replace(">", " >").replace("  ", " ");
    }
    return Html.fromHtml(source);
}

From source file:org.solovyev.android.calculator.widget.CalculatorWidget.java

@Nonnull
private SpannedString initCursorString(@Nonnull Context context) {
    if (cursorString == null) {
        final SpannableString s = App.colorString("|",
                ContextCompat.getColor(context, R.color.cpp_widget_cursor));
        // this will override any other style span (f.e. italic)
        s.setSpan(new StyleSpan(Typeface.NORMAL), 0, 1, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
        cursorString = new SpannedString(s);
    }/*from  w  w  w  .ja v a2s.  c o m*/
    return cursorString;
}

From source file:com.pax.pay.trans.action.activity.InputTransData2Activity.java

private void setEditText_date(EditText editText) {
    SpannableString ss = new SpannableString(getString(R.string.prompt_date_default2));
    AbsoluteSizeSpan ass = new AbsoluteSizeSpan(getResources().getDimensionPixelOffset(R.dimen.font_size_large),
            false);/*from w  w  w .  ja  v  a 2s  . c om*/
    ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    editText.setHint(new SpannedString(ss)); // ??,?
    editText.setHintTextColor(getResources().getColor(R.color.textEdit_hint));
    editText.setInputType(InputType.TYPE_CLASS_NUMBER);
    editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(4) });
}

From source file:me.oriley.homage.Homage.java

public void addLicense(@NonNull String key, @NonNull String name, @NonNull String url,
        @NonNull String description) {
    addLicense(key, name, url, new SpannedString(description));
}

From source file:com.adkdevelopment.earthquakesurvival.data.syncadapter.SyncAdapter.java

@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {//  w ww.j av  a2 s  .  co m

    Context context = getContext();

    App.getApiManager().getEarthquakeService().getData().enqueue(new Callback<EarthquakeObject>() {
        @Override
        public void onResponse(Call<EarthquakeObject> call, Response<EarthquakeObject> response) {
            EarthquakeObject earthquake = response.body();

            Vector<ContentValues> cVVector = new Vector<>(earthquake.getFeatures().size());

            double currentBiggest = 0.0;
            ContentValues notifyValues = null;

            for (Feature each : earthquake.getFeatures()) {

                ContentValues earthquakeValues = new ContentValues();

                earthquakeValues.put(EarthquakeColumns.PLACE, each.getProperties().getPlace());
                earthquakeValues.put(EarthquakeColumns.ID_EARTH, each.getId());
                earthquakeValues.put(EarthquakeColumns.MAG, each.getProperties().getMag());
                earthquakeValues.put(EarthquakeColumns.TYPE, each.getProperties().getType());
                earthquakeValues.put(EarthquakeColumns.ALERT, each.getProperties().getAlert());
                earthquakeValues.put(EarthquakeColumns.TIME, each.getProperties().getTime());
                earthquakeValues.put(EarthquakeColumns.URL, each.getProperties().getUrl());
                earthquakeValues.put(EarthquakeColumns.DETAIL, each.getProperties().getDetail());
                earthquakeValues.put(EarthquakeColumns.DEPTH, each.getGeometry().getCoordinates().get(2));
                earthquakeValues.put(EarthquakeColumns.LONGITUDE, each.getGeometry().getCoordinates().get(0));
                earthquakeValues.put(EarthquakeColumns.LATITUDE, each.getGeometry().getCoordinates().get(1));

                LatLng latLng = new LatLng(each.getGeometry().getCoordinates().get(1),
                        each.getGeometry().getCoordinates().get(0));
                LatLng location = LocationUtils.getLocation(context);
                earthquakeValues.put(EarthquakeColumns.DISTANCE, LocationUtils.getDistance(latLng, location));

                cVVector.add(earthquakeValues);

                if (each.getProperties().getMag() != null && each.getProperties().getMag() > currentBiggest) {
                    currentBiggest = each.getProperties().getMag();
                    notifyValues = new ContentValues(earthquakeValues);
                    notifyValues.put(EarthquakeColumns.PLACE,
                            Utilities.formatEarthquakePlace(each.getProperties().getPlace()));
                }
            }

            int inserted = 0;
            // add to database
            ContentResolver resolver = context.getContentResolver();

            if (cVVector.size() > 0) {
                ContentValues[] cvArray = new ContentValues[cVVector.size()];
                cVVector.toArray(cvArray);
                inserted = resolver.bulkInsert(EarthquakeColumns.CONTENT_URI, cvArray);
            }

            // Set the date to day minus one to delete old data from the database
            Date date = new Date();
            date.setTime(date.getTime() - DateUtils.DAY_IN_MILLIS);

            int deleted = resolver.delete(EarthquakeColumns.CONTENT_URI, EarthquakeColumns.TIME + " <= ?",
                    new String[] { String.valueOf(date.getTime()) });
            Log.v(TAG, "Service Complete. " + inserted + " Inserted, " + deleted + " deleted");
            sendNotification(notifyValues);
        }

        @Override
        public void onFailure(Call<EarthquakeObject> call, Throwable t) {
            Log.e(TAG, "onFailure: " + t.toString());
        }
    });

    App.getNewsManager().getNewsService().getNews().enqueue(new Callback<Rss>() {
        @Override
        public void onResponse(Call<Rss> call, Response<Rss> response) {
            Channel news = response.body().getChannel();

            Vector<ContentValues> cVVector = new Vector<>(news.getItem().size());

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z",
                    Locale.getDefault());
            Date date = new Date();

            for (Item each : news.getItem()) {

                ContentValues weatherValues = new ContentValues();

                try {
                    date = simpleDateFormat.parse(each.getPubDate());
                } catch (ParseException e) {
                    Log.e(TAG, "e:" + e);
                }

                weatherValues.put(NewsColumns.DATE, date.getTime());
                weatherValues.put(NewsColumns.TITLE, each.getTitle());
                weatherValues.put(NewsColumns.DESCRIPTION,
                        Html.toHtml(new SpannedString(each.getDescription())));
                weatherValues.put(NewsColumns.URL, each.getLink());
                weatherValues.put(NewsColumns.GUID, each.getGuid().getContent());

                cVVector.add(weatherValues);
            }

            int inserted = 0;
            // add to database
            ContentResolver resolver = getContext().getContentResolver();

            if (cVVector.size() > 0) {

                // Student: call bulkInsert to add the weatherEntries to the database here
                ContentValues[] cvArray = new ContentValues[cVVector.size()];
                cVVector.toArray(cvArray);
                inserted = resolver.bulkInsert(NewsColumns.CONTENT_URI, cvArray);
            }

            // Set the date to day minus two to delete old data from the database
            date = new Date();
            date.setTime(date.getTime() - DateUtils.DAY_IN_MILLIS * 3);

            int deleted = resolver.delete(NewsColumns.CONTENT_URI, NewsColumns.DATE + " <= ?",
                    new String[] { String.valueOf(date.getTime()) });
        }

        @Override
        public void onFailure(Call<Rss> call, Throwable t) {
            Log.e(TAG, "onFailure: " + t.toString());
        }
    });

    // TODO: 4/22/16 possible refactoring 
    //checking the last update and notify if it' the first of the day
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String lastNotificationKey = context.getString(R.string.sharedprefs_key_last_countupdate);
    long lastSync = prefs.getLong(lastNotificationKey, DateUtils.DAY_IN_MILLIS);

    if (System.currentTimeMillis() - lastSync >= Utilities.getSyncIntervalPrefs(context)
            * DateUtils.SECOND_IN_MILLIS) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
        Date date = new Date(System.currentTimeMillis());

        String startTime[] = new String[] { simpleDateFormat.format(date.getTime() - DateUtils.YEAR_IN_MILLIS),
                simpleDateFormat.format(date.getTime() - DateUtils.DAY_IN_MILLIS * 30),
                simpleDateFormat.format(date.getTime() - DateUtils.WEEK_IN_MILLIS),
                simpleDateFormat.format(date.getTime() - DateUtils.DAY_IN_MILLIS) };

        String endTime = simpleDateFormat.format(date);

        int iterator = 1;
        while (iterator < CountColumns.ALL_COLUMNS.length) {
            final int round = iterator;

            App.getApiManager().getEarthquakeService().getEarthquakeStats(startTime[round - 1], endTime)
                    .enqueue(new Callback<CountEarthquakes>() {
                        @Override
                        public void onResponse(Call<CountEarthquakes> call,
                                Response<CountEarthquakes> response) {
                            ContentValues count = new ContentValues();
                            count.put(CountColumns.ALL_COLUMNS[round], response.body().getCount());

                            ContentResolver contentResolver = context.getContentResolver();

                            Cursor cursor = contentResolver.query(CountColumns.CONTENT_URI, null, null, null,
                                    null);

                            if (cursor != null) {
                                if (cursor.getCount() < 1) {
                                    long inserted = ContentUris
                                            .parseId(contentResolver.insert(CountColumns.CONTENT_URI, count));
                                    //Log.d(TAG, "inserted:" + inserted);
                                } else {
                                    int updated = contentResolver.update(CountColumns.CONTENT_URI, count,
                                            CountColumns._ID + " = ?", new String[] { "1" });
                                    //Log.d(TAG, "updated: " + updated);
                                }
                                cursor.close();
                            }

                        }

                        @Override
                        public void onFailure(Call<CountEarthquakes> call, Throwable t) {
                            Log.e(TAG, "Error: " + t);
                        }
                    });
            iterator++;
        }

        //refreshing last sync
        prefs.edit().putLong(lastNotificationKey, System.currentTimeMillis()).apply();
    }

    // notify PagerActivity that data has been updated
    context.getContentResolver().notifyChange(EarthquakeColumns.CONTENT_URI, null, false);
    context.getContentResolver().notifyChange(NewsColumns.CONTENT_URI, null, false);
    context.getContentResolver().notifyChange(CountColumns.CONTENT_URI, null, false);

    updateWidgets();
}

From source file:com.digipom.manteresting.android.adapter.NailCursorAdapter.java

private CachedData cacheDataAndGet(Context context, Cursor cursor, int requestedWidth) throws JSONException {
    final String nailId = cursor.getString(nailIdColumnIndex);

    CachedData cachedDataForThisNailItem = cachedData.get(nailId);

    if (cachedDataForThisNailItem == null) {
        cachedDataForThisNailItem = new CachedData();

        final JSONObject nailObject = new JSONObject(cursor.getString(nailObjectColumnIndex));

        cachedDataForThisNailItem.originalImageUriString = nailObject.getString("original");
        cachedDataForThisNailItem.nailDescription = nailObject.getString("description");

        final String userName = nailObject.getJSONObject("user").getString("username");
        final String userNameFirstLetterCapitalised = userName.substring(0, 1).toUpperCase()
                + userName.substring(1);
        final String workBench = nailObject.getJSONObject("workbench").getString("title");

        cachedDataForThisNailItem.styledUserAndCategory = Html.fromHtml(String.format(
                Html.toHtml(new SpannedString(context.getResources().getText(R.string.nailUserAndCategory))),
                userNameFirstLetterCapitalised, workBench));

        cachedData.put(nailId, cachedDataForThisNailItem);
    }/* w  w  w . jav  a 2s.  c  o m*/

    // Request a bitmap load.
    if (!failedDownloads.contains(cachedDataForThisNailItem.originalImageUriString)
            && serviceConnector.getService() != null) {
        serviceConnector.getService().loadOnlyLifoAsync(cachedDataForThisNailItem.originalImageUriString,
                requestedWidth);
    }

    return cachedDataForThisNailItem;
}

From source file:com.taobao.weex.dom.WXTextDomObject.java

/**
 * Truncate the source span to the specified lines.
 * Caller of this method must ensure that the lines of text is <strong>greater than desired lines and need truncate</strong>.
 * Otherwise, unexpected behavior may happen.
 * @param source The source span./*from   www. j  a  v  a 2 s . com*/
 * @param paint the textPaint
 * @param desired specified lines.
 * @param truncateAt truncate method, null value means clipping overflow text directly, non-null value means using ellipsis strategy to clip
 * @return The spans after clipped.
 */
private @NonNull Spanned truncate(@Nullable Editable source, @NonNull TextPaint paint, int desired,
        @Nullable TextUtils.TruncateAt truncateAt) {
    Spanned ret = new SpannedString("");
    if (!TextUtils.isEmpty(source) && source.length() > 0) {
        if (truncateAt != null) {
            source.append(ELLIPSIS);
            Object[] spans = source.getSpans(0, source.length(), Object.class);
            for (Object span : spans) {
                int start = source.getSpanStart(span);
                int end = source.getSpanEnd(span);
                if (start == 0 && end == source.length() - 1) {
                    source.removeSpan(span);
                    source.setSpan(span, 0, source.length(), source.getSpanFlags(span));
                }
            }
        }

        StaticLayout layout;
        int startOffset;

        while (source.length() > 1) {
            startOffset = source.length() - 1;
            if (truncateAt != null) {
                startOffset -= 1;
            }
            source.delete(startOffset, startOffset + 1);
            layout = new StaticLayout(source, paint, desired, Layout.Alignment.ALIGN_NORMAL, 1, 0, false);
            if (layout.getLineCount() <= 1) {
                ret = source;
                break;
            }
        }
    }
    return ret;
}

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

public static CharSequence stringOrSpannedString(CharSequence source) {
    if (source == null)
        return null;
    if (source instanceof SpannedString)
        return source;
    if (source instanceof Spanned)
        return new SpannedString(source);

    return source.toString();
}