android.text.style.TypefaceSpan Java Examples

The following examples show how to use android.text.style.TypefaceSpan. 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 File: InterfaceFragment.java    From Dashchan with Apache License 2.0 6 votes vote down vote up
@Override
public void onPreferenceAfterChange(Preference preference) {
	super.onPreferenceAfterChange(preference);
	if (preference == advancedSearchPreference && advancedSearchPreference.isChecked()) {
		SpannableStringBuilder builder = new SpannableStringBuilder
				(getText(R.string.preference_advanced_search_message));
		Object[] spans = builder.getSpans(0, builder.length(), Object.class);
		for (Object span : spans) {
			int start = builder.getSpanStart(span);
			int end = builder.getSpanEnd(span);
			int flags = builder.getSpanFlags(span);
			builder.removeSpan(span);
			builder.setSpan(new TypefaceSpan("sans-serif-medium"), start, end, flags);
		}
		MessageDialog.create(this, builder, false);
	}
}
 
Example #2
Source File: PassphrasePromptActivity.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private void initializeResources() {
  Toolbar     toolbar  = findViewById(R.id.toolbar);

  passphraseAuthContainer = findViewById(R.id.password_auth_container);
  passphraseLayout        = findViewById(R.id.passphrase_layout);
  passphraseInput         = findViewById(R.id.passphrase_input);
  okButton                = findViewById(R.id.ok_button);
  successView             = findViewById(R.id.success);

  setSupportActionBar(toolbar);
  getSupportActionBar().setTitle("");

  SpannableString hint = new SpannableString(getString(R.string.PassphrasePromptActivity_enter_passphrase));
  hint.setSpan(new RelativeSizeSpan(0.9f), 0, hint.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
  hint.setSpan(new TypefaceSpan("sans-serif-light"), 0, hint.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

  passphraseInput.setHint(hint);
  passphraseInput.setOnEditorActionListener(new PassphraseActionListener());

  okButton.setOnClickListener(v -> handlePassphrase());
}
 
Example #3
Source File: PassphrasePromptActivity.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
private void initializeResources() {
  getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
  getSupportActionBar().setCustomView(R.layout.centered_app_title);

  ImageButton okButton = (ImageButton) findViewById(R.id.ok_button);
  passphraseText       = (EditText)    findViewById(R.id.passphrase_edit);
  SpannableString hint = new SpannableString("  " + getString(R.string.PassphrasePromptActivity_enter_passphrase));
  hint.setSpan(new RelativeSizeSpan(0.9f), 0, hint.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
  hint.setSpan(new TypefaceSpan("sans-serif"), 0, hint.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

  passphraseText.setHint(hint);
  okButton.setOnClickListener(new OkButtonClickListener());
  passphraseText.setOnEditorActionListener(new PassphraseActionListener());
  passphraseText.setImeActionLabel(getString(R.string.prompt_passphrase_activity__unlock),
                                   EditorInfo.IME_ACTION_DONE);
}
 
Example #4
Source File: HtmlFontTagHandler.java    From Markwon with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(@NonNull MarkwonVisitor visitor, @NonNull MarkwonHtmlRenderer renderer, @NonNull HtmlTag tag) {

    if (tag.isBlock()) {
        visitChildren(visitor, renderer, tag.getAsBlock());
    }

    final String font = tag.attributes().get("name");
    if (!TextUtils.isEmpty(font)) {
        SpannableBuilder.setSpans(
                visitor.builder(),
                new TypefaceSpan(font),
                tag.start(),
                tag.end()
        );
    }
}
 
Example #5
Source File: UserAutoRunCommandHelper.java    From revolution-irc with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void showDialog(Activity activity) {
    super.showDialog(activity);
    dismissDialog(activity);
    AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
    dialog.setTitle(R.string.connection_error_command_title);

    StringBuilder commands = new StringBuilder();
    for (String cmd : mCommands) {
        commands.append('/');
        commands.append(cmd);
        commands.append('\n');
    }
    SpannableString commandsSeq = new SpannableString(commands);
    commandsSeq.setSpan(new TypefaceSpan("monospace"), 0, commandsSeq.length(),
            SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
    dialog.setMessage(SpannableStringHelper.format(activity.getResources().getQuantityText(
            R.plurals.connection_error_command_dialog_content, mCommands.size()),
            mNetworkName, commandsSeq));
    dialog.setPositiveButton(R.string.action_ok, null);
    dialog.setOnDismissListener((DialogInterface di) -> {
        dismiss();
    });
    mDialog = dialog.show();
}
 
Example #6
Source File: PreTagHandler.java    From mvvm-template with GNU General Public License v3.0 6 votes vote down vote up
@Override public void handleTagNode(TagNode node, SpannableStringBuilder builder, int start, int end) {
    if (isPre) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("\n");//fake padding top + make sure, pre is always by itself
        getPlainText(buffer, node);
        buffer.append("\n");//fake padding bottom + make sure, pre is always by itself
        builder.append(replace(buffer.toString()));
        builder.append("\n");
        builder.setSpan(new CodeBackgroundRoundedSpan(color), start, builder.length(), SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.append("\n");
        this.appendNewLine(builder);
        this.appendNewLine(builder);
    } else {
        StringBuffer text = node.getText();
        builder.append(" ");
        builder.append(replace(text.toString()));
        builder.append(" ");
        final int stringStart = start + 1;
        final int stringEnd = builder.length() - 1;
        builder.setSpan(new BackgroundColorSpan(color), stringStart, stringEnd, SPAN_EXCLUSIVE_EXCLUSIVE);
        if (theme == PrefGetter.LIGHT) {
            builder.setSpan(new ForegroundColorSpan(Color.RED), stringStart, stringEnd, SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        builder.setSpan(new TypefaceSpan("monospace"), stringStart, stringEnd, SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}
 
Example #7
Source File: CheckFragment.java    From bither-android with Apache License 2.0 5 votes vote down vote up
private SpannableString getSpannableStringFromAddress(String address) {
    address = Utils.shortenAddress(address);
    String a = address.substring(0, 4);
    String str = String.format(
            getString(R.string.check_address_private_key_title),
            address);
    int indexOfAddress = str.indexOf(a);
    SpannableString spannable = new SpannableString(str);
    spannable.setSpan(new TypefaceSpan("monospace"), indexOfAddress,
            indexOfAddress + 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return spannable;
}
 
Example #8
Source File: ExpandablePreferenceGroup.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Set the title for the preference group.
 * @param resourceId The resource id of the text to use.
 * @param count The number of entries the preference group contains.
 */
public void setGroupTitle(int resourceId, int count) {
    SpannableStringBuilder spannable =
            new SpannableStringBuilder(getContext().getResources().getString(resourceId));
    String prefCount = String.format(Locale.getDefault(), " - %d", count);
    spannable.append(prefCount);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        spannable.setSpan(new StyleSpan(android.graphics.Typeface.BOLD),
                   0,
                   spannable.length() - prefCount.length(),
                   Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    } else {
        spannable.setSpan(new TypefaceSpan("sans-serif-medium"),
                   0,
                   spannable.length() - prefCount.length(),
                   Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    // Color the first part of the title blue.
    ForegroundColorSpan blueSpan = new ForegroundColorSpan(
            ApiCompatibilityUtils.getColor(getContext().getResources(),
                    R.color.pref_accent_color));
    spannable.setSpan(blueSpan, 0, spannable.length() - prefCount.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    // Gray out the total count of items.
    int gray = ApiCompatibilityUtils.getColor(getContext().getResources(),
            R.color.expandable_group_dark_gray);
    spannable.setSpan(new ForegroundColorSpan(gray),
               spannable.length() - prefCount.length(),
               spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    setTitle(spannable);
}
 
Example #9
Source File: WalletUtils.java    From bither-android with Apache License 2.0 5 votes vote down vote up
public static Editable formatHash(@Nullable final String prefix,
                                  @Nonnull final String address, final int groupSize,
                                  final int lineSize, final char groupSeparator) {
    final SpannableStringBuilder builder = prefix != null ? new SpannableStringBuilder(
            prefix) : new SpannableStringBuilder();
    if (address == null) {
        return builder;
    }
    final int len = address.length();
    for (int i = 0;
         i < len;
         i += groupSize) {
        final int end = i + groupSize;
        final String part = address.substring(i, end < len ? end : len);

        builder.append(part);
        builder.setSpan(new TypefaceSpan("monospace"), builder.length()
                        - part.length(), builder.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        );
        if (end < len) {
            final boolean endOfLine = lineSize > 0 && end % lineSize == 0;
            builder.append(endOfLine ? '\n' : groupSeparator);
        }
    }

    return builder;
}
 
Example #10
Source File: TextDecorator.java    From text-decorator with Apache License 2.0 5 votes vote down vote up
public TextDecorator setTypeface(final String family, final String... texts) {
  int index;

  for (String text : texts) {
    if (content.contains(text)) {
      index = content.indexOf(text);
      decoratedContent.setSpan(new TypefaceSpan(family), index, index + text.length(), flags);
    }
  }

  return this;
}
 
Example #11
Source File: Highlighter.java    From writeily-pro with MIT License 5 votes vote down vote up
private void createMonospaceSpanForMatches(Editable e, Pattern pattern) {

        createSpanForMatches(e, pattern, new SpanCreator() {
            @Override
            public ParcelableSpan create(Matcher m) {
                return new TypefaceSpan("monospace");
            }
        });

    }
 
Example #12
Source File: FontPreferenceCompat.java    From Stringlate with MIT License 5 votes vote down vote up
private void loadFonts(Context context, @Nullable AttributeSet attrs) {
    _defaultValue = _fontValues[0];
    if (attrs != null) {
        for (int i = 0; i < attrs.getAttributeCount(); i++) {
            String attrName = attrs.getAttributeName(i);
            String attrValue = attrs.getAttributeValue(i);
            if (attrName.equalsIgnoreCase("defaultValue")) {
                if (attrValue.startsWith("@")) {
                    int resId = Integer.valueOf(attrValue.substring(1));
                    attrValue = getContext().getString(resId);
                }
                _defaultValue = attrValue;
                break;
            }
        }
    }

    Spannable[] fontText = new Spannable[_fontNames.length];
    for (int i = 0; i < _fontNames.length; i++) {
        fontText[i] = new SpannableString(_fontNames[i] + "\n" + _fontValues[i]);
        fontText[i].setSpan(new TypefaceSpan(_fontValues[i]), 0, _fontNames[i].length(), 0);
        fontText[i].setSpan(new RelativeSizeSpan(0.7f), _fontNames[i].length() + 1, fontText[i].length(), 0);

    }
    setDefaultValue(_defaultValue);
    setEntries(fontText);
    setEntryValues(_fontValues);
}
 
Example #13
Source File: Html.java    From ForPDA with GNU General Public License v3.0 5 votes vote down vote up
private static void endFont(Editable text) {
    Font font = getLast(text, Font.class);
    if (font != null) {
        setSpanFromMark(text, font, new TypefaceSpan(font.mFace));
    }
    Foreground foreground = getLast(text, Foreground.class);
    if (foreground != null) {
        setSpanFromMark(text, foreground,
                new ForegroundColorSpan(foreground.mForegroundColor));
    }
}
 
Example #14
Source File: Utils.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Formats the app name using "sans-serif" and then appends the summary after a space with
 * "sans-serif-light". Doesn't mandate any font sizes or any other styles, that is up to the
 * {@link android.widget.TextView} which it ends up being displayed in.
 */
public static CharSequence formatAppNameAndSummary(String appName, String summary) {
    String toFormat = appName + ' ' + summary;
    CharacterStyle normal = new TypefaceSpan("sans-serif");
    CharacterStyle light = new TypefaceSpan("sans-serif-light");

    SpannableStringBuilder sb = new SpannableStringBuilder(toFormat);
    sb.setSpan(normal, 0, appName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    sb.setSpan(light, appName.length(), toFormat.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    return sb;
}
 
Example #15
Source File: ExpandablePreferenceGroup.java    From delion with Apache License 2.0 5 votes vote down vote up
/**
 * Set the title for the preference group.
 * @param resourceId The resource id of the text to use.
 * @param count The number of entries the preference group contains.
 */
public void setGroupTitle(int resourceId, int count) {
    SpannableStringBuilder spannable =
            new SpannableStringBuilder(getContext().getResources().getString(resourceId));
    String prefCount = String.format(Locale.getDefault(), " - %d", count);
    spannable.append(prefCount);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        spannable.setSpan(new StyleSpan(android.graphics.Typeface.BOLD),
                   0,
                   spannable.length() - prefCount.length(),
                   Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    } else {
        spannable.setSpan(new TypefaceSpan("sans-serif-medium"),
                   0,
                   spannable.length() - prefCount.length(),
                   Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    // Color the first part of the title blue.
    ForegroundColorSpan blueSpan = new ForegroundColorSpan(
            ApiCompatibilityUtils.getColor(getContext().getResources(),
                    R.color.pref_accent_color));
    spannable.setSpan(blueSpan, 0, spannable.length() - prefCount.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    // Gray out the total count of items.
    int gray = ApiCompatibilityUtils.getColor(getContext().getResources(),
            R.color.expandable_group_dark_gray);
    spannable.setSpan(new ForegroundColorSpan(gray),
               spannable.length() - prefCount.length(),
               spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    setTitle(spannable);
}
 
Example #16
Source File: JidDialog.java    From Conversations with GNU General Public License v3.0 5 votes vote down vote up
public static SpannableString style(Context context, @StringRes int res, String... args) {
    SpannableString spannable = new SpannableString(context.getString(res, (Object[]) args));
    if (args.length >= 1) {
        final String value = args[0];
        int start = spannable.toString().indexOf(value);
        if (start >= 0) {
            spannable.setSpan(new TypefaceSpan("monospace"), start, start + value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    return spannable;
}
 
Example #17
Source File: Html.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private static void endFont(Editable text) {
    Font font = getLast(text, Font.class);
    if (font != null) {
        setSpanFromMark(text, font, new TypefaceSpan(font.mFace));
    }

    Foreground foreground = getLast(text, Foreground.class);
    if (foreground != null) {
        setSpanFromMark(text, foreground,
                new ForegroundColorSpan(foreground.mForegroundColor));
    }
}
 
Example #18
Source File: GeolocationSnackbarController.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Shows the geolocation snackbar if it hasn't already been shown and the geolocation snackbar
 * is currently relevant: i.e. the default search engine is Google, location is enabled
 * for Chrome, the tab is not incognito, etc.
 *
 * @param snackbarManager The SnackbarManager used to show the snackbar.
 * @param view Any view that's attached to the view hierarchy.
 * @param isIncognito Whether the currently visible tab is incognito.
 * @param delayMs The delay in ms before the snackbar should be shown. This is intended to
 *                give the keyboard time to animate in.
 */
public static void maybeShowSnackbar(final SnackbarManager snackbarManager, View view,
        boolean isIncognito, int delayMs) {
    final Context context = view.getContext();
    if (ChromeFeatureList.isEnabled(ChromeFeatureList.CONSISTENT_OMNIBOX_GEOLOCATION)) return;
    if (getGeolocationSnackbarShown(context)) return;

    // If in incognito mode, don't show the snackbar now, but maybe show it later.
    if (isIncognito) return;

    if (neverShowSnackbar(context)) {
        setGeolocationSnackbarShown(context);
        return;
    }

    Uri searchUri = Uri.parse(TemplateUrlService.getInstance().getUrlForSearchQuery("foo"));
    TypefaceSpan robotoMediumSpan = new TypefaceSpan("sans-serif-medium");
    String messageWithoutSpans = context.getResources().getString(
            R.string.omnibox_geolocation_disclosure, "<b>" + searchUri.getHost() + "</b>");
    SpannableString message = SpanApplier.applySpans(messageWithoutSpans,
            new SpanInfo("<b>", "</b>", robotoMediumSpan));
    String settings = context.getResources().getString(R.string.preferences);
    int durationMs = DeviceClassManager.isAccessibilityModeEnabled(view.getContext())
            ? ACCESSIBILITY_SNACKBAR_DURATION_MS : SNACKBAR_DURATION_MS;
    final GeolocationSnackbarController controller = new GeolocationSnackbarController();
    final Snackbar snackbar = Snackbar
            .make(message, controller, Snackbar.TYPE_ACTION, Snackbar.UMA_OMNIBOX_GEOLOCATION)
            .setAction(settings, view)
            .setSingleLine(false)
            .setDuration(durationMs);

    view.postDelayed(new Runnable() {
        @Override
        public void run() {
            snackbarManager.dismissSnackbars(controller);
            snackbarManager.showSnackbar(snackbar);
            setGeolocationSnackbarShown(context);
        }
    }, delayMs);
}
 
Example #19
Source File: AKHtml.java    From Mupdf with Apache License 2.0 5 votes vote down vote up
private static void endFont(Editable text) {
    Font font = getLast(text, Font.class);
    if (font != null) {
        setSpanFromMark(text, font, new TypefaceSpan(font.mFace));
    }

    Foreground foreground = getLast(text, Foreground.class);
    if (foreground != null) {
        setSpanFromMark(text, foreground,
                new ForegroundColorSpan(foreground.mForegroundColor));
    }
}
 
Example #20
Source File: FromTextView.java    From deltachat-android with GNU General Public License v3.0 5 votes vote down vote up
public void setText(Recipient recipient, boolean read) {
  String fromString = recipient.toShortString();

  int typeface;

  if (!read) {
    typeface = Typeface.BOLD;
  } else {
    typeface = Typeface.NORMAL;
  }

  SpannableStringBuilder builder = new SpannableStringBuilder();

  SpannableString fromSpan = new SpannableString(fromString);
  fromSpan.setSpan(new StyleSpan(typeface), 0, builder.length(),
                   Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

  if (recipient.getName() == null && !TextUtils.isEmpty(recipient.getProfileName())) {
    SpannableString profileName = new SpannableString(" (~" + recipient.getProfileName() + ") ");
    profileName.setSpan(new CenterAlignedRelativeSizeSpan(0.75f), 0, profileName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    profileName.setSpan(new TypefaceSpan("sans-serif-light"), 0, profileName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    profileName.setSpan(new ForegroundColorSpan(ResUtil.getColor(getContext(), R.attr.conversation_list_item_subject_color)), 0, profileName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    if (ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL){
      builder.append(profileName);
      builder.append(fromSpan);
    } else {
      builder.append(fromSpan);
      builder.append(profileName);
    }
  } else {
    builder.append(fromSpan);
  }

  setText(builder);
}
 
Example #21
Source File: Tx3gDecoder.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("ReferenceEquality")
private static void attachFontFamily(SpannableStringBuilder cueText, String fontFamily,
    String defaultFontFamily, int start, int end, int spanPriority) {
  if (fontFamily != defaultFontFamily) {
    cueText.setSpan(new TypefaceSpan(fontFamily), start, end,
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | spanPriority);
  }
}
 
Example #22
Source File: Html.java    From Nimingban with Apache License 2.0 5 votes vote down vote up
private static void endFont(SpannableStringBuilder text) {
    int len = text.length();
    Object obj = getLast(text, Font.class);
    int where = text.getSpanStart(obj);

    text.removeSpan(obj);

    if (where != len) {
        Font f = (Font) obj;

        if (!TextUtils.isEmpty(f.mColor)) {
            if (f.mColor.startsWith("@")) {
                Resources res = Resources.getSystem();
                String name = f.mColor.substring(1);
                int colorRes = res.getIdentifier(name, "color", "android");
                text.setSpan(new TextAppearanceSpan(null, 0, 0, ColorStateList.valueOf(res.getColor(colorRes)), null),
                        where, len,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else {
                try {
                    int c = getHtmlColor(f.mColor);
                    text.setSpan(new ForegroundColorSpan(c | 0xFF000000),
                            where, len,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                } catch (ParseException e) {
                    // Ignore
                }
            }
        }

        if (f.mFace != null) {
            text.setSpan(new TypefaceSpan(f.mFace), where, len,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
}
 
Example #23
Source File: CustomHtmlToSpannedConverter.java    From zulip-android with Apache License 2.0 5 votes vote down vote up
private static void endFont(SpannableStringBuilder text) {
    int len = text.length();
    Object obj = getLast(text, Font.class);
    int where = text.getSpanStart(obj);

    text.removeSpan(obj);

    if (where != len) {
        Font f = (Font) obj;

        if (!TextUtils.isEmpty(f.mColor)) {
            if (f.mColor.startsWith("@")) {
                Resources res = Resources.getSystem();
                String name = f.mColor.substring(1);
                int colorRes = res.getIdentifier(name, "color", "android");
                if (colorRes != 0) {
                    ColorStateList colors = res.getColorStateList(colorRes);
                    text.setSpan(new TextAppearanceSpan(null, 0, 0, colors,
                                    null), where, len,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            } else {
                int c = getHtmlColor(f.mColor);
                if (c != -1) {
                    text.setSpan(new ForegroundColorSpan(c | 0xFF000000),
                            where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
        }

        if (f.mFace != null) {
            text.setSpan(new TypefaceSpan(f.mFace), where, len,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
}
 
Example #24
Source File: StylingHelper.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
private static ParcelableSpan clone(ParcelableSpan span) {
    if (span instanceof ForegroundColorSpan) {
        return new ForegroundColorSpan(((ForegroundColorSpan) span).getForegroundColor());
    } else if (span instanceof TypefaceSpan) {
        return new TypefaceSpan(((TypefaceSpan) span).getFamily());
    } else if (span instanceof StyleSpan) {
        return new StyleSpan(((StyleSpan) span).getStyle());
    } else if (span instanceof StrikethroughSpan) {
        return new StrikethroughSpan();
    } else {
        throw new AssertionError("Unknown Span");
    }
}
 
Example #25
Source File: StylingHelper.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
private static ParcelableSpan createSpanForStyle(ImStyleParser.Style style) {
    switch (style.getKeyword()) {
        case "*":
            return new StyleSpan(Typeface.BOLD);
        case "_":
            return new StyleSpan(Typeface.ITALIC);
        case "~":
            return new StrikethroughSpan();
        case "`":
        case "```":
            return new TypefaceSpan("monospace");
        default:
            throw new AssertionError("Unknown Style");
    }
}
 
Example #26
Source File: JidDialog.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
public static SpannableString style(Context context, @StringRes int res, String... args) {
    SpannableString spannable = new SpannableString(context.getString(res, (Object[]) args));
    if (args.length >= 1) {
        final String value = args[0];
        int start = spannable.toString().indexOf(value);
        if (start >= 0) {
            spannable.setSpan(new TypefaceSpan("monospace"), start, start + value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    return spannable;
}
 
Example #27
Source File: ContentsFragment.java    From Dashchan with Apache License 2.0 5 votes vote down vote up
private CharSequence makeSubdirDescrption() {
	String[] formats = {"\\c", "\\d", "\\b", "\\t", "\\e", "<\u2026>"};
	String[] descriptions = getResources().getStringArray(R.array.preference_subdirectory_pattern_descriptions);
	SpannableStringBuilder builder = new SpannableStringBuilder();
	for (int i = 0; i < formats.length; i++) {
		if (builder.length() > 0) {
			builder.append('\n');
		}
		StringUtils.appendSpan(builder, formats[i], new TypefaceSpan("sans-serif-medium"));
		builder.append(" — ");
		builder.append(descriptions[i]);
	}
	return builder;
}
 
Example #28
Source File: GeolocationSnackbarController.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Shows the geolocation snackbar if it hasn't already been shown and the geolocation snackbar
 * is currently relevant: i.e. the default search engine is Google, location is enabled
 * for Chrome, the tab is not incognito, etc.
 *
 * @param snackbarManager The SnackbarManager used to show the snackbar.
 * @param view Any view that's attached to the view hierarchy.
 * @param isIncognito Whether the currently visible tab is incognito.
 * @param delayMs The delay in ms before the snackbar should be shown. This is intended to
 *                give the keyboard time to animate in.
 */
public static void maybeShowSnackbar(final SnackbarManager snackbarManager, View view,
        boolean isIncognito, int delayMs) {
    final Context context = view.getContext();
    if (ChromeFeatureList.isEnabled(ChromeFeatureList.CONSISTENT_OMNIBOX_GEOLOCATION)) return;
    if (getGeolocationSnackbarShown(context)) return;

    // If in incognito mode, don't show the snackbar now, but maybe show it later.
    if (isIncognito) return;

    if (neverShowSnackbar(context)) {
        setGeolocationSnackbarShown(context);
        return;
    }

    Uri searchUri = Uri.parse(TemplateUrlService.getInstance().getUrlForSearchQuery("foo"));
    TypefaceSpan robotoMediumSpan = new TypefaceSpan("sans-serif-medium");
    String messageWithoutSpans = context.getResources().getString(
            R.string.omnibox_geolocation_disclosure, "<b>" + searchUri.getHost() + "</b>");
    SpannableString message = SpanApplier.applySpans(messageWithoutSpans,
            new SpanInfo("<b>", "</b>", robotoMediumSpan));
    String settings = context.getResources().getString(R.string.preferences);
    int durationMs = AccessibilityUtil.isAccessibilityEnabled()
            ? ACCESSIBILITY_SNACKBAR_DURATION_MS : SNACKBAR_DURATION_MS;
    final GeolocationSnackbarController controller = new GeolocationSnackbarController();
    final Snackbar snackbar = Snackbar
            .make(message, controller, Snackbar.TYPE_ACTION, Snackbar.UMA_OMNIBOX_GEOLOCATION)
            .setAction(settings, view)
            .setSingleLine(false)
            .setDuration(durationMs);

    view.postDelayed(new Runnable() {
        @Override
        public void run() {
            snackbarManager.dismissSnackbars(controller);
            snackbarManager.showSnackbar(snackbar);
            setGeolocationSnackbarShown(context);
        }
    }, delayMs);
}
 
Example #29
Source File: ExpandablePreferenceGroup.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Set the title for the preference group.
 * @param resourceId The resource id of the text to use.
 * @param count The number of entries the preference group contains.
 */
public void setGroupTitle(int resourceId, int count) {
    SpannableStringBuilder spannable =
            new SpannableStringBuilder(getContext().getResources().getString(resourceId));
    String prefCount = String.format(Locale.getDefault(), " - %d", count);
    spannable.append(prefCount);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        spannable.setSpan(new StyleSpan(android.graphics.Typeface.BOLD),
                   0,
                   spannable.length() - prefCount.length(),
                   Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    } else {
        spannable.setSpan(new TypefaceSpan("sans-serif-medium"),
                   0,
                   spannable.length() - prefCount.length(),
                   Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    // Color the first part of the title blue.
    ForegroundColorSpan blueSpan = new ForegroundColorSpan(
            ApiCompatibilityUtils.getColor(getContext().getResources(),
                    R.color.pref_accent_color));
    spannable.setSpan(blueSpan, 0, spannable.length() - prefCount.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    // Gray out the total count of items.
    int gray = ApiCompatibilityUtils.getColor(getContext().getResources(),
            R.color.expandable_group_dark_gray);
    spannable.setSpan(new ForegroundColorSpan(gray),
               spannable.length() - prefCount.length(),
               spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    setTitle(spannable);
}
 
Example #30
Source File: HtmlParser.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
private static void endFont(SpannableStringBuilder text) {
    int len = text.length();
    Object obj = getLast(text, Font.class);
    int where = text.getSpanStart(obj);

    text.removeSpan(obj);

    if (where != len) {
        Font f = (Font) obj;

        if (!TextUtils.isEmpty(f.mColor)) {
            if (f.mColor.startsWith("@")) {
                Resources res = Resources.getSystem();
                String name = f.mColor.substring(1);
                int colorRes = res.getIdentifier(name, "color", "android");
                if (colorRes != 0) {
                    ColorStateList colors = CompatibilityUtils.getColorStateList(res, colorRes);
                    text.setSpan(new TextAppearanceSpan(null, 0, 0, colors, null), where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            } else {
                int c = ColorHidden.getHtmlColor(f.mColor);
                if (c != -1) {
                    text.setSpan(new ForegroundColorSpan(c | 0xFF000000), where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
        }

        if (f.mFace != null) {
            text.setSpan(new TypefaceSpan(f.mFace), where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        
        if (f.mStyle != null) {
            List<Object> styleSpans = parseStyleAttributes(f.mStyle);
            for (Object span : styleSpans) {
                text.setSpan(span, where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
    }
}