Example usage for android.text SpannableString SpannableString

List of usage examples for android.text SpannableString SpannableString

Introduction

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

Prototype

public SpannableString(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

public static CharSequence handleTextUrl(CharSequence content) {
    Matcher m = URL_PATTERN.matcher(content);

    Spannable spannable = null;// www .java  2 s  . c om
    while (m.find()) {
        // Ensure spannable
        if (spannable == null) {
            if (content instanceof Spannable) {
                spannable = (Spannable) content;
            } else {
                spannable = new SpannableString(content);
            }
        }

        int start = m.start();
        int end = m.end();

        URLSpan[] links = spannable.getSpans(start, end, URLSpan.class);
        if (links.length > 0) {
            // There has been URLSpan already, leave it alone
            continue;
        }

        URLSpan urlSpan = new URLSpan(m.group(0));
        spannable.setSpan(urlSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    return spannable == null ? content : spannable;
}

From source file:Main.java

/**
 * Applies the given style to a range of the input CharSequence.
 * @param style The style to apply (see the style constants in {@link Typeface}).
 * @param input The CharSequence to style.
 * @param start Starting index of the range to style (will be clamped to be a minimum of 0).
 * @param end Ending index of the range to style (will be clamped to a maximum of the input
 *     length).//from   www . j a va 2 s. c o m
 * @param flags Bitmask for configuring behavior of the span.  See {@link android.text.Spanned}.
 * @return The styled CharSequence.
 */
public static CharSequence applyStyleToSpan(int style, CharSequence input, int start, int end, int flags) {
    // Enforce bounds of the char sequence.
    start = Math.max(0, start);
    end = Math.min(input.length(), end);
    SpannableString text = new SpannableString(input);
    text.setSpan(new StyleSpan(style), start, end, flags);
    return text;
}

From source file:Main.java

public static CharSequence replace(Context context, String text) {
    if (TextUtils.isEmpty(text)) {
        return text;
    }//from ww  w . j  a  v  a2  s . co  m
    SpannableString spannableString = new SpannableString(text);
    Matcher matcher = pattern.matcher(text);
    while (matcher.find()) {
        String factText = matcher.group();
        String key = factText.substring(1, factText.length() - 1);
        if (contain(emojiCodes, factText)) {
            Bitmap bitmap = getEmojiDrawable(context, key);
            ImageSpan image = new ImageSpan(context, bitmap);
            int start = matcher.start();
            int end = matcher.end();
            spannableString.setSpan(image, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    return spannableString;
}

From source file:com.jamesgiang.aussnowcam.Utils.java

public static void About(Context c) {
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(c);
    dialogBuilder.setTitle(R.string.app_name);
    dialogBuilder.setIcon(R.drawable.icon);
    TextView textView = new TextView(c);
    SpannableString s = new SpannableString(c.getString(R.string.about_info));
    Linkify.addLinks(s, Linkify.WEB_URLS);
    textView.setText(s);//from   w  w w.j a  va  2s. co  m
    textView.setGravity(Gravity.CENTER);
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    dialogBuilder.setView(textView);
    dialogBuilder.show();
}

From source file:Main.java

public static void setTitle(TextView titleTv, int titleColor, int titleTextSize, int messageColor,
        int messageTextSize, CharSequence title, CharSequence message) {
    titleTv.setMinHeight(titleTextSize * 3);

    if (!TextUtils.isEmpty(title) && TextUtils.isEmpty(message)) {
        titleTv.setTextColor(titleColor);
        titleTv.setTextSize(TypedValue.COMPLEX_UNIT_PX, titleTextSize);
        titleTv.getPaint().setFakeBoldText(true);
        titleTv.setText(title);//  w  ww  .  j  a v  a  2 s .  co m
    } else if (TextUtils.isEmpty(title) && !TextUtils.isEmpty(message)) {
        titleTv.setTextColor(messageColor);
        titleTv.setTextSize(TypedValue.COMPLEX_UNIT_PX, messageTextSize);
        titleTv.setText(message);
    } else if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(message)) {
        SpannableString titleSs = new SpannableString(title + "\n" + message);
        titleSs.setSpan(new ForegroundColorSpan(titleColor), 0, title.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        titleSs.setSpan(new AbsoluteSizeSpan(titleTextSize), 0, title.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        titleSs.setSpan(new StyleSpan(Typeface.BOLD), 0, title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        titleSs.setSpan(new ForegroundColorSpan(messageColor), title.length(), titleSs.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        titleSs.setSpan(new AbsoluteSizeSpan(messageTextSize), title.length(), titleSs.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        titleTv.setText(titleSs);
        titleTv.setLineSpacing(0.0f, 1.2f);
    } else {
        titleTv.setVisibility(View.GONE);
    }
}

From source file:Main.java

public static void showChangelog(final Context context, final String title, final String appname,
        final int resChanges, final int resNotes) {
    final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
    final String v0 = p.getString(PREFS_LAST_RUN, "");
    String v1 = null;/*w  ww .java2s . c  o  m*/
    try {
        v1 = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
    } catch (NameNotFoundException e) {
        Log.e(TAG, "package not found: " + context.getPackageName(), e);
    }
    p.edit().putString(PREFS_LAST_RUN, v1).commit();
    if (v0.length() == 0) {
        Log.d(TAG, "first boot, skip changelog");
        // return;
    }
    if (v0.equals(v1)) {
        Log.d(TAG, "no changes");
        return;
    }

    String[] changes = context.getResources().getStringArray(resChanges);
    String[] notes = resNotes > 0 ? context.getResources().getStringArray(resNotes) : null;

    final SpannableStringBuilder sb = new SpannableStringBuilder();
    for (String s : notes) {
        SpannableString ss = new SpannableString(s + "\n");
        int j = s.indexOf(":");
        if (j > 0) {
            if (!TextUtils.isEmpty(s)) {
                ss.setSpan(new StyleSpan(Typeface.BOLD), 0, j, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        sb.append(ss);
        sb.append("\n");
    }
    if (notes != null && notes.length > 0) {
        sb.append("\n");
    }
    for (String s : changes) {
        s = appname + " " + s.replaceFirst(": ", ":\n* ").replaceAll(", ", "\n* ") + "\n";
        SpannableString ss = new SpannableString(s);
        int j = s.indexOf(":");
        if (j > 0) {
            ss.setSpan(new StyleSpan(Typeface.BOLD), 0, j, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        sb.append(ss);
        sb.append("\n");
    }
    sb.setSpan(new RelativeSizeSpan(0.75f), 0, sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    changes = null;
    notes = null;

    AlertDialog.Builder b = new AlertDialog.Builder(context);
    b.setTitle(title);
    b.setMessage(sb);
    b.setCancelable(true);
    b.setPositiveButton(android.R.string.ok, null);
    b.show();
}

From source file:com.contralabs.inmap.fragments.LegalNoticesDialogFragment.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Context context = getActivity();

    ScrollView scrollView = new ScrollView(context);
    // Set up the TextView
    final TextView message = new TextView(context);
    // We'll use a spannablestring to be able to make links clickable
    final SpannableString s = new SpannableString(
            GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(context));

    // Set some padding
    int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10,
            getResources().getDisplayMetrics());
    message.setPadding(padding, padding, padding, padding);
    // Set up the final string
    message.setText(s);/*  www.j  a  v  a 2s . co m*/
    scrollView.addView(message);
    // Now linkify the text
    Linkify.addLinks(message, Linkify.ALL);
    Linkify.addLinks(message, Pattern.compile("@([A-Za-z0-9_-]+)"), "https://twitter.com/#!/");
    return new AlertDialog.Builder(getActivity()).setTitle(R.string.legal_notices).setCancelable(true)
            .setIcon(R.drawable.ic_launcher)
            .setPositiveButton(context.getString(R.string.voltar), (OnClickListener) null).setView(scrollView)
            .create();
}

From source file:com.fuzz.emptyhusk.BoldTextCellGenerator.java

@NonNull
@Override/*from   ww  w.  j  av a 2s .co m*/
protected Spannable getTextFor(@NonNull Context context, int position) {
    String[] introStrings = context.getResources().getStringArray(R.array.introductory_messages);

    SpannableString ssb = new SpannableString(introStrings[position]);
    MigratoryStyleSpan span = new MigratoryStyleSpan(BOLD);

    // Order matters when setting spans. The base color must be in place first

    ForegroundColorSpan colorSpan = new ForegroundColorSpan(
            ContextCompat.getColor(context, R.color.colorSecondary));
    ssb.setSpan(colorSpan, 0, ssb.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);

    // Only then should custom MigratorySpans be set.

    MigratoryRange<Integer> coverage = span.getCoverage(ssb);
    int start = coverage.getLower();
    int end = coverage.getUpper();
    ssb.setSpan(span, start, end, span.preferredFlags(0));

    MigratoryForegroundColorSpan boldColorSpan = new MigratoryForegroundColorSpan(
            ContextCompat.getColor(context, R.color.colorAccent));
    ssb.setSpan(boldColorSpan, start, end, boldColorSpan.preferredFlags(0));

    return ssb;
}

From source file:Main.java

@Nullable
private static CharSequence getEllipsizedTextWithSettingScaleX(@Nullable final CharSequence text,
        final int maxWidth, @Nonnull final TextPaint paint) {
    if (text == null) {
        return null;
    }/*w  ww .ja  v a2  s.  c  om*/
    final float scaleX = getTextScaleX(text, maxWidth, paint);
    if (scaleX >= MIN_TEXT_XSCALE) {
        paint.setTextScaleX(scaleX);
        return text;
    }

    // <code>text</code> must be ellipsized with minimum text scale x.
    paint.setTextScaleX(MIN_TEXT_XSCALE);
    final boolean hasBoldStyle = hasStyleSpan(text, BOLD_SPAN);
    final boolean hasUnderlineStyle = hasStyleSpan(text, UNDERLINE_SPAN);
    // TextUtils.ellipsize erases any span object existed after ellipsized point.
    // We have to restore these spans afterward.
    final CharSequence ellipsizedText = TextUtils.ellipsize(text, paint, maxWidth, TextUtils.TruncateAt.MIDDLE);
    if (!hasBoldStyle && !hasUnderlineStyle) {
        return ellipsizedText;
    }
    final Spannable spannableText = (ellipsizedText instanceof Spannable) ? (Spannable) ellipsizedText
            : new SpannableString(ellipsizedText);
    if (hasBoldStyle) {
        addStyleSpan(spannableText, BOLD_SPAN);
    }
    if (hasUnderlineStyle) {
        addStyleSpan(spannableText, UNDERLINE_SPAN);
    }
    return spannableText;
}

From source file:com.nasageek.utexasutilities.activities.AboutMeActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.aboutme_layout);

    actionbar = getSupportActionBar();/*from ww w  .j  ava2s.com*/
    actionbar.setTitle("About");
    actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionbar.setHomeButtonEnabled(true);
    actionbar.setDisplayHomeAsUpEnabled(true);

    // force the License Dialog link to be underlined so it looks "linky"
    TextView licenseView = (TextView) findViewById(R.id.library_license_link);
    SpannableString underlinedLicenseLink = new SpannableString(getString(R.string.library_license_link));
    underlinedLicenseLink.setSpan(new UnderlineSpan(), 0, underlinedLicenseLink.length(), 0);
    licenseView.setText(underlinedLicenseLink);
    licenseView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            FragmentManager fm = getSupportFragmentManager();
            LibraryLicenseDialog libraryLicenseDlg = new LibraryLicenseDialog();
            libraryLicenseDlg.show(fm, "fragment_license");
        }
    });
    // do the same thing with the Privacy Policy link
    TextView policyView = (TextView) findViewById(R.id.privacy_policy_link);
    SpannableString underlinedPolicyLink = new SpannableString(getString(R.string.privacy_policy_link));
    underlinedPolicyLink.setSpan(new UnderlineSpan(), 0, underlinedPolicyLink.length(), 0);
    policyView.setText(underlinedPolicyLink);
    policyView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            FragmentManager fm = getSupportFragmentManager();
            PrivacyPolicyDialog privacyPolicyDlg = new PrivacyPolicyDialog();
            privacyPolicyDlg.show(fm, "fragment_privacy_policy");
        }
    });

    TextView versionNumberView = (TextView) findViewById(R.id.version);
    String versionName = "";
    try {
        versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
    } catch (NameNotFoundException e) {
        // of course UTilities is installed...
        e.printStackTrace();
    }
    versionNumberView.setText(versionName);
}