private static void AppendProjectText(this SpannableStringBuilder spannable, ProjectSpan projectSpan) { /* HACK: This unbreakable space is needed because of a bug in * the way android handles ReplacementSpans. It makes sure that * all token boundaries can't be changed by the soft input once * they are set. */ var start = spannable.Length(); spannable.Append(unbreakableSpace); spannable.Append(projectSpan.ProjectName); if (!string.IsNullOrEmpty(projectSpan.TaskName)) { spannable.Append($": {projectSpan.TaskName}"); } spannable.Append(unbreakableSpace); var end = spannable.Length(); var projectTokenSpan = new ProjectTokenSpan( projectSpan.ProjectId, projectSpan.ProjectName, projectSpan.ProjectColor, projectSpan.TaskId, projectSpan.TaskName ); spannable.SetSpan(projectTokenSpan, start, end, SpanTypes.ExclusiveExclusive); spannable.SetSpan(new RelativeSizeSpan(spanSizeProportion), start, end, SpanTypes.ExclusiveExclusive); }
private static ISpanned HighLightExcerptText(string excerptText) { var ssb = new SpannableStringBuilder(excerptText); ssb.SetSpan(new BackgroundColorSpan(HighlightBackgroundColor), 0, excerptText.Length, 0); return(ssb); }
public static ISpanned CreateStyledString(TextStyleParameters style, string text, int startIndex = 0, int endIndex = -1) { if (endIndex == -1) { endIndex = text.Length; } if (startIndex >= endIndex) { throw new Exception("Unable to create styled string, StartIndex is too high:" + startIndex); } // Parse the text text = ParseString(style, text); var isHTML = (!string.IsNullOrEmpty(text) && Common.MatchHtmlTags.IsMatch(text)); if (isHTML) { return(CreateHtmlString(text, style.Name)); } else { var builder = new SpannableStringBuilder(text); var font = instance.GetFont(style.Font); var span = new CustomTypefaceSpan("", font, style); builder.SetSpan(span, startIndex, endIndex, SpanTypes.ExclusiveExclusive); return(builder); } }
protected virtual ISpanned GetSnackbarText(ToastConfig cfg) { var sb = new SpannableStringBuilder(); string message = cfg.Message; var hasIcon = (cfg.Icon != null); if (hasIcon) { message = "\u2002\u2002" + message; // add 2 spaces, 1 for the image the next for spacing between text and image } sb.Append(message); if (hasIcon) { var drawable = cfg.Icon.ToNative(); drawable.SetBounds(0, 0, drawable.IntrinsicWidth, drawable.IntrinsicHeight); sb.SetSpan(new ImageSpan(drawable, SpanAlign.Bottom), 0, 1, SpanTypes.ExclusiveExclusive); } if (cfg.MessageTextColor != null) { sb.SetSpan( new ForegroundColorSpan(cfg.MessageTextColor.Value.ToNative()), 0, sb.Length(), SpanTypes.ExclusiveExclusive ); } return(sb); }
private void SetText(TextView control, string html) { var htmlLabel = (HtmlLabel)Element; // Set the type of content and the custom tag list handler using var listTagHandler = new ListTagHandler(htmlLabel.AndroidListIndent); // KWI-FIX: added AndroidListIndent parameter var imageGetter = new UrlImageParser(Control); FromHtmlOptions fromHtmlOptions = htmlLabel.AndroidLegacyMode ? FromHtmlOptions.ModeLegacy : FromHtmlOptions.ModeCompact; ISpanned sequence = Build.VERSION.SdkInt >= BuildVersionCodes.N ? Html.FromHtml(html, fromHtmlOptions, imageGetter, listTagHandler) : Html.FromHtml(html, imageGetter, listTagHandler); using var strBuilder = new SpannableStringBuilder(sequence); // Make clickable links if (!Element.GestureRecognizers.Any()) { control.MovementMethod = LinkMovementMethod.Instance; URLSpan[] urls = strBuilder .GetSpans(0, sequence.Length(), Class.FromType(typeof(URLSpan))) .Cast <URLSpan>() .ToArray(); foreach (URLSpan span in urls) { MakeLinkClickable(strBuilder, span); } } // Android adds an unnecessary "\n" that must be removed using ISpanned value = RemoveLastChar(strBuilder); // Finally sets the value of the TextView control.SetText(value, TextView.BufferType.Spannable); }
private void SetTextViewHtml(TextView text, string html) { // Tells the TextView that the content is HTML and adds a custom TagHandler var sequence = Build.VERSION.SdkInt >= BuildVersionCodes.N ? Html.FromHtml(html, FromHtmlOptions.ModeCompact, null, new ListTagHandler()) : #pragma warning disable 618 Html.FromHtml(html, null, new ListTagHandler()); #pragma warning restore 618 // Makes clickable links text.MovementMethod = LinkMovementMethod.Instance; var strBuilder = new SpannableStringBuilder(sequence); var urls = strBuilder.GetSpans(0, sequence.Length(), Class.FromType(typeof(URLSpan))); foreach (var span in urls) { MakeLinkClickable(strBuilder, (URLSpan)span); } var value = RemoveLastChar(strBuilder); // Finally sets the value of the TextView text.SetText(value, TextView.BufferType.Spannable); }
public virtual void RebindTags (TimeEntryTagsView tagsView) { List<String> tagList = new List<String> (); String t; if (tagsView == null || tagsView.IsLoading) { return; } if (tagsView.Count == 0) { EditText.Text = String.Empty; return; } foreach (String tagText in tagsView.Data) { t = tagText.Length > TagMaxLength ? tagText.Substring (0, TagMaxLength - 1).Trim () + "…" : tagText; if (tagText.Length > 0) { tagList.Add (t); } } // The extra whitespace prevents the ImageSpans and the text they are over // to break at different positions, leaving zero linespacing on edge cases. var tags = new SpannableStringBuilder (String.Join (" ", tagList) + " "); int x = 0; foreach (String tagText in tagList) { tags.SetSpan (new ImageSpan (MakeTagChip (tagText)), x, x + tagText.Length, SpanTypes.ExclusiveExclusive); x = x + tagText.Length + 1; } EditText.SetText (tags, EditText.BufferType.Spannable); }
private static bool HasAnimatedSpans(SpannableStringBuilder spannableBuilder) { var spans = spannableBuilder.GetSpans(0, spannableBuilder.Length(), Class.FromType(typeof(CustomTypefaceSpan))); return(spans.OfType <CustomTypefaceSpan>().Any(customTypefaceSpan => customTypefaceSpan.Animated)); }
public static ICharSequence Parse(Context context, IList<IconFontDescriptorWrapper> iconFontDescriptors, ICharSequence text, TextView target) { context = context.ApplicationContext; // Analyse the text and replace {} blocks With the appropriate character // Retain all transformations in the accumulator var spannableBuilder = new SpannableStringBuilder(text); RecursivePrepareSpannableIndexes(context, text.ToString(), spannableBuilder, iconFontDescriptors, 0); var isAnimated = HasAnimatedSpans(spannableBuilder); // If animated, periodically invalidate the TextView so that the // CustomTypefaceSpan can redraw itself if (isAnimated) { if (target == null) { throw new ArgumentException("You can't use \"spin\" without providing the target TextView."); } if (!(target is IHasOnViewAttachListener)) { throw new ArgumentException(target.GetType().Name + " does not implement " + "HasOnViewAttachListener. Please use IconTextView, IconButton or IconToggleButton."); } ((IHasOnViewAttachListener) target).OnViewAttachListener = new OnViewAttachListenerOnViewAttachListenerAnonymousInnerClassHelper(target); } else if (target is IHasOnViewAttachListener) { ((IHasOnViewAttachListener) target).OnViewAttachListener = null; } return spannableBuilder; }
/// <summary> /// Add a button and a text link and their tapping events to the initial page. /// </summary> /// <param name="consentDialogView"></param> private void AddInitButtonAndLinkClick(View consentDialogView) { consentYesBtn = consentDialogView.FindViewById <Button>(Resource.Id.btn_consent_init_yes); consentNoBtn = consentDialogView.FindViewById <Button>(Resource.Id.btn_consent_init_skip); consentNoBtn.SetOnClickListener(this); consentYesBtn.SetOnClickListener(this); initInfoTv = consentDialogView.FindViewById <TextView>(Resource.Id.consent_center_init_content); initInfoTv.MovementMethod = ScrollingMovementMethod.Instance; string initText = context.GetString(Resource.String.consent_init_text); SpannableStringBuilder spanInitText = new SpannableStringBuilder(initText); // Set the listener on the event for tapping some text. ClickableSpan initTouchHere = new InitTouchHere(this); ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.ParseColor("#0000FF")); int initTouchHereStart = context.Resources.GetInteger(Resource.Integer.init_here_start); int initTouchHereEnd = context.Resources.GetInteger(Resource.Integer.init_here_end); spanInitText.SetSpan(initTouchHere, initTouchHereStart, initTouchHereEnd, SpanTypes.ExclusiveExclusive); spanInitText.SetSpan(colorSpan, initTouchHereStart, initTouchHereEnd, SpanTypes.ExclusiveExclusive); initInfoTv.TextFormatted = spanInitText; initInfoTv.MovementMethod = LinkMovementMethod.Instance; }
public override IEditable Replace(int start, int end, ICharSequence tb, int tbstart, int tbend) { // Create a copy of this string builder to preview the change, allowing the TextBox's event handlers to act on the modified text. var copy = new SpannableStringBuilder(this); copy.Replace(start, end, tb, tbstart, tbend); var previewText = copy.ToString(); var finalText = Owner.ProcessTextInput(previewText); if (Owner._wasLastEditModified = previewText != finalText) { // Text was modified. Use new text as the replacement string, re-applying spans to ensure EditText's and keyboard's internals aren't disrupted. ICharSequence replacement; if (tb is ISpanned spanned) { var spannable = new SpannableString(finalText); TextUtils.CopySpansFrom(spanned, tbstart, Min(tbend, spannable.Length()), null, spannable, 0); replacement = spannable; } else { replacement = new Java.Lang.String(finalText); } base.Replace(0, Length(), replacement, 0, finalText.Length); } else { // Text was not modified, use original replacement ICharSequence base.Replace(start, end, tb, tbstart, tbend); } return(this); }
public override View GetView(int position, View convertView, ViewGroup parent) { View row = convertView; if (row == null) { LayoutInflater inflater = ((Activity)Context).LayoutInflater; row = inflater.Inflate(viewResourceId, parent, false); } row.FindViewById <TextView>(Resource.Id.BroName).Text = bros.First(b => b.Id == items[position].Bro).Name; var amountsBuilder = new SpannableStringBuilder(); var amount = items[position].Amount.WithAccuracy(baseCurrency.Accuracy); var amountString = new SpannableString(String.Format(culture, "{0:0.#} {1}", amount, baseCurrency.Name)); ForegroundColorSpan foregroundColor; foregroundColor = amount > 0 ? new ForegroundColorSpan(Color.Green) : (amount < 0 ? new ForegroundColorSpan(Color.Red) : new ForegroundColorSpan(Color.Gray)); amountString.SetSpan(foregroundColor, 0, amountString.Length(), SpanTypes.Composing); amountsBuilder.Append(amountString); row.FindViewById <TextView>(Resource.Id.BroAmounts).SetText(amountsBuilder, TextView.BufferType.Spannable); return(row); }
private static bool HasAnimatedSpans(SpannableStringBuilder spannableBuilder) { CustomTypefaceSpan[] spans = spannableBuilder.GetSpans(0, spannableBuilder.Length(), Class.FromType(typeof(CustomTypefaceSpan))).Cast <CustomTypefaceSpan>().ToArray(); return(spans.Any(span => span.Animated)); }
public static Java.Lang.ICharSequence Parse(Context context, IList<IIconModule> modules, Java.Lang.ICharSequence text, View target = null) { context = context.ApplicationContext; // Analyse the text and replace {} blocks with the appropriate character // Retain all transformations in the accumulator var builder = new SpannableStringBuilder(text); RecursivePrepareSpannableIndexes(context, text.ToString(), builder, modules, 0); var isAnimated = HasAnimatedSpans(builder); // If animated, periodically invalidate the TextView so that the // CustomTypefaceSpan can redraw itself if (isAnimated) { if (target == null) throw new ArgumentException("You can't use \"spin\" without providing the target View."); if (!(target is IHasOnViewAttachListener)) throw new ArgumentException(target.Class.SimpleName + " does not implement " + "HasOnViewAttachListener. Please use IconTextView, IconButton or IconToggleButton."); ((IHasOnViewAttachListener)target).SetOnViewAttachListener(new MyListener(target)); } else if (target is IHasOnViewAttachListener) { ((IHasOnViewAttachListener)target).SetOnViewAttachListener(null); } return builder; }
private void InitClickableSpan() { // Add a text-based tapping event. protocolTV.MovementMethod = ScrollingMovementMethod.Instance; string privacyInfoText = context.GetString(Resource.String.protocol_content_text); SpannableStringBuilder spanPrivacyInfoText = new SpannableStringBuilder(privacyInfoText); //Set the listener on the event for tapping some text. ClickableSpan adsAndPrivacyTouchHere = new AdsAndPrivacyTouchHere(this); ClickableSpan personalizedAdsTouchHere = new PersonalizedAdsTouchHere(this); ForegroundColorSpan colorPrivacy = new ForegroundColorSpan(Color.ParseColor("#0000FF")); ForegroundColorSpan colorPersonalize = new ForegroundColorSpan(Color.ParseColor("#0000FF")); int privacyTouchHereStart = context.Resources.GetInteger(Resource.Integer.privacy_start); int privacyTouchHereEnd = context.Resources.GetInteger(Resource.Integer.privacy_end); int personalizedTouchHereStart = context.Resources.GetInteger(Resource.Integer.personalized_start); int personalizedTouchHereEnd = context.Resources.GetInteger(Resource.Integer.personalized_end); spanPrivacyInfoText.SetSpan(adsAndPrivacyTouchHere, privacyTouchHereStart, privacyTouchHereEnd, SpanTypes.ExclusiveExclusive); spanPrivacyInfoText.SetSpan(colorPrivacy, privacyTouchHereStart, privacyTouchHereEnd, SpanTypes.ExclusiveExclusive); spanPrivacyInfoText.SetSpan(personalizedAdsTouchHere, personalizedTouchHereStart, personalizedTouchHereEnd, SpanTypes.ExclusiveExclusive); spanPrivacyInfoText.SetSpan(colorPersonalize, personalizedTouchHereStart, personalizedTouchHereEnd, SpanTypes.ExclusiveExclusive); protocolTV.TextFormatted = spanPrivacyInfoText; protocolTV.MovementMethod = LinkMovementMethod.Instance; }
//JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static CharSequence parse(android.content.Context context, java.util.List<IconFontDescriptorWrapper> iconFontDescriptors, CharSequence text, final android.widget.TextView target) public static CharSequence parse(Context context, IList <IconFontDescriptorWrapper> iconFontDescriptors, CharSequence text, TextView target) { context = context.ApplicationContext; // Analyse the text and replace {} blocks with the appropriate character // Retain all transformations in the accumulator //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final android.text.SpannableStringBuilder spannableBuilder = new android.text.SpannableStringBuilder(text); SpannableStringBuilder spannableBuilder = new SpannableStringBuilder(text); recursivePrepareSpannableIndexes(context, text.ToString(), spannableBuilder, iconFontDescriptors, 0); bool isAnimated = hasAnimatedSpans(spannableBuilder); // If animated, periodically invalidate the TextView so that the // CustomTypefaceSpan can redraw itself if (isAnimated) { if (target == null) { throw new System.ArgumentException("You can't use \"spin\" without providing the target TextView."); } if (!(target is HasOnViewAttachListener)) { throw new System.ArgumentException(target.GetType().Name + " does not implement " + "HasOnViewAttachListener. Please use IconTextView, IconButton or IconToggleButton."); } ((HasOnViewAttachListener)target).OnViewAttachListener = new HasOnViewAttachListener_OnViewAttachListenerAnonymousInnerClassHelper(target); } else if (target is HasOnViewAttachListener) { ((HasOnViewAttachListener)target).OnViewAttachListener = null; } return(spannableBuilder); }
public AutoLinkTextView(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr) { SpanColors = new Dictionary <AutoLinkType, Color>(); MovementMethod = AccurateMovementMethod.Instance; _spanBuilder = new SpannableStringBuilder(); var attr_s = context.ObtainStyledAttributes(attrs, Resource.Styleable.AutoLinkTextView); try { Flags = attr_s.GetInt(Resource.Styleable.AutoLinkTextView_linkModes, -1); SpanColors.Add(AutoLinkType.Hashtag, attr_s.GetColor(Resource.Styleable.AutoLinkTextView_hashtagColor, Color.Red)); SpanColors.Add(AutoLinkType.Mention, attr_s.GetColor(Resource.Styleable.AutoLinkTextView_mentionColor, Color.Red)); SpanColors.Add(AutoLinkType.Phone, attr_s.GetColor(Resource.Styleable.AutoLinkTextView_phoneColor, Color.Black)); SpanColors.Add(AutoLinkType.Email, attr_s.GetColor(Resource.Styleable.AutoLinkTextView_emailColor, Color.Red)); SpanColors.Add(AutoLinkType.Url, attr_s.GetColor(Resource.Styleable.AutoLinkTextView_urlColor, Color.Red)); SelectedColor = attr_s.GetColor(Resource.Styleable.AutoLinkTextView_selectedColor, Color.LightGray); UnderlineEnabled = attr_s.GetBoolean(Resource.Styleable.AutoLinkTextView_underlineEnabled, false); if (attr_s.HasValue(Resource.Styleable.AutoLinkTextView_android_text)) { AutoLinkText = attr_s.GetString(Resource.Styleable.AutoLinkTextView_android_text); } } finally { attr_s.Recycle(); } }
private void SetStyle() { var styledLabel = (ExtendedLabel)this.Element; if (styledLabel.Children != null && styledLabel.Children.Count > 0) { SpannableStringBuilder builder = new SpannableStringBuilder(); styledLabel.Children.ToList().ForEach(child => { var spannableText = new SpannableString(child.Text); spannableText.SetSpan(new ForegroundColorSpan(child.CustomFont.Color.ToAndroid()), 0, child.Text.Length, SpanTypes.Composing); spannableText.SetSpan(new CustomTypefaceSpan(child.CustomFont), 0, child.Text.Length, SpanTypes.Composing); if (child.Command != null) { var clickableSpan = new CustomClickableSpan(); clickableSpan.Click += (Android.Views.View obj) => { child.Command?.Execute(child.CommandParameter); }; spannableText.SetSpan(clickableSpan, 0, child.Text.Length, SpanTypes.Composing); } builder.Append(spannableText); }); Control.TextFormatted = builder; Control.MovementMethod = new LinkMovementMethod(); return; } if (styledLabel.Text != null && styledLabel.CustomFont != null) { styledLabel.CustomFont.ApplyTo(Control); } }
public static ISpannable ToProjectTaskClient(bool hasProject, string project, string projectColor, string task, string client) { if (!hasProject) { return(new SpannableString(string.Empty)); } var spannableString = new SpannableStringBuilder(); spannableString.Append( project, new ForegroundColorSpan(Color.ParseColor(projectColor)), SpanTypes.ExclusiveInclusive); if (!string.IsNullOrEmpty(task)) { spannableString.Append($": {task}"); } if (!string.IsNullOrEmpty(client)) { spannableString.Append( $" {client}", new ForegroundColorSpan(Color.ParseColor(ClientNameColor)), SpanTypes.ExclusiveExclusive); } return(spannableString); }
public void BindViewHolder(UniversalViewHolder holder, int position) { if (MedicineList != null && position < MedicineList.Count) { var medicine = MedicineList[position]; var selectionBox = holder.GetView <ImageView>(Resource.Id.selectionBox); var medicineName = holder.GetView <TextView>(Resource.Id.medicineName); var separator = holder.GetView <View>(Resource.Id.separator); separator.Visibility = position == MedicineList.Count - 1 ? ViewStates.Gone : ViewStates.Visible; selectionBox.Selected = selectedMedicines.Contains(medicine); var strengthText = $", {medicine.Strength}"; var totalText = medicine.Name + strengthText; var formattedText = new SpannableStringBuilder(totalText); formattedText.SetSpan(new StyleSpan(TypefaceStyle.Bold), 0, medicine.Name.Length, SpanTypes.InclusiveInclusive); formattedText.SetSpan(new AbsoluteSizeSpan(18.ConvertToPixel(activity)), 0, medicine.Name.Length, SpanTypes.InclusiveInclusive); formattedText.SetSpan(new StyleSpan(TypefaceStyle.Normal), medicine.Name.Length, totalText.Length, SpanTypes.InclusiveInclusive); formattedText.SetSpan(new AbsoluteSizeSpan(14.ConvertToPixel(activity)), medicine.Name.Length, totalText.Length, SpanTypes.InclusiveInclusive); medicineName.TextFormatted = formattedText; } }
private ICharSequence SetMenuItemFont(string text, int resId) { SpannableStringBuilder sb = new SpannableStringBuilder(text); sb.SetSpan(new TextAppearanceSpan(this, resId), 0, text.Length, 0); return(sb); }
/// <summary> /// Parses the specified context. /// </summary> /// <param name="context">The context.</param> /// <param name="modules">The modules.</param> /// <param name="text">The text.</param> /// <param name="size">The size.</param> /// <param name="target">The target.</param> /// <returns></returns> /// <exception cref="System.ArgumentException"> /// You can't use \spin\ without providing the target View. /// or /// </exception> public static Java.Lang.ICharSequence Parse(Context context, IList <IIconModule> modules, Java.Lang.ICharSequence text, Single size, View target = null) { context = context.ApplicationContext; // Analyse the text and replace {} blocks with the appropriate character // Retain all transformations in the accumulator var builder = new SpannableStringBuilder(text); RecursivePrepareSpannableIndexes(context, text.ToString(), size, builder, modules, 0); var isAnimated = HasAnimatedSpans(builder); // If animated, periodically invalidate the TextView so that the // CustomTypefaceSpan can redraw itself if (isAnimated) { if (target == null) { throw new ArgumentException("You can't use \"spin\" without providing the target View."); } if (!(target is IHasOnViewAttachListener)) { throw new ArgumentException(target.Class.SimpleName + " does not implement " + "HasOnViewAttachListener. Please use IconTextView, IconButton or IconToggleButton."); } ((IHasOnViewAttachListener)target).SetOnViewAttachListener(new MyListener(target)); } else if (target is IHasOnViewAttachListener) { ((IHasOnViewAttachListener)target).SetOnViewAttachListener(null); } return(builder); }
public static ISpannable ToProjectTaskClient(Context context, bool hasProject, string project, string projectColor, string task, string client, bool projectIsPlaceholder, bool taskIsPlaceholder, bool displayPlaceholders = false) { if (!hasProject) { return(new SpannableString(string.Empty)); } var spannableString = new SpannableStringBuilder(); appendProjectTextAndSpans(context, project, projectColor, projectIsPlaceholder, displayPlaceholders, spannableString); appendTaskTextAndSpans(context, task, projectIsPlaceholder, taskIsPlaceholder, displayPlaceholders, spannableString); if (!string.IsNullOrEmpty(client)) { spannableString.Append($" {client}", new ForegroundColorSpan(Color.ParseColor(ClientNameColor)), SpanTypes.ExclusiveExclusive); } return(spannableString); }
public bool OnActionItemClicked(ActionMode mode, IMenuItem item) { CharacterStyle cs; int start = edt.SelectionStart; int end = edt.SelectionEnd; SpannableStringBuilder ssb = new SpannableStringBuilder(edt.Text); switch (item.ItemId) { case Resource.Id.bold: cs = new StyleSpan(TypefaceStyle.Bold); ssb.SetSpan(cs, start, end, SpanTypes.ExclusiveExclusive); edt.Text = ssb.ToString(); return(true); case Resource.Id.italic: cs = new StyleSpan(TypefaceStyle.Italic); ssb.SetSpan(cs, start, end, SpanTypes.ExclusiveExclusive); edt.Text = ssb.ToString(); return(true); case Resource.Id.underline: cs = new UnderlineSpan(); ssb.SetSpan(cs, start, end, SpanTypes.ExclusiveExclusive); edt.Text = ssb.ToString(); return(true); case Resource.Id.strikethrough: cs = new StrikethroughSpan(); ssb.SetSpan(cs, start, end, SpanTypes.ExclusiveExclusive); edt.Text = ssb.ToString(); return(true); } return(false); }
/// <summary> /// Ends a Header tag. /// </summary> /// <returns>void</returns> /// <param name="text">SpannableStringBuilder</param> static void endHeader(SpannableStringBuilder text) { int len = text.Length(); var obj = getLast(text, Java.Lang.Class.FromType(typeof(Header))); int where = text.GetSpanStart(obj); text.RemoveSpan(obj); // Back off not to change only the text, not the blank line. while (len > where && text.CharAt(len - 1) == '\n') { len--; } if (where != len) { Header h = (Header)obj; text.SetSpan(new RelativeSizeSpan(HEADER_SIZES [h.mLevel]), where, len, SpanTypes.ExclusiveExclusive); text.SetSpan(new StyleSpan(TypefaceStyle.Bold), where, len, SpanTypes.ExclusiveExclusive); } }
public void BindViewHolder(UniversalViewHolder holder, int position) { if (MedicineReminderList != null && position < MedicineReminderList.Count) { var medicineReminder = MedicineReminderList[position]; var medicineName = holder.GetView <TextView>(Resource.Id.medicineName); var reminderDetails = holder.GetView <TextView>(Resource.Id.reminderDetails); var strengthText = $", {medicineReminder.Medicine.Strength}"; var totalText = medicineReminder.Medicine.Name + strengthText; var formattedText = new SpannableStringBuilder(totalText); formattedText.SetSpan(new StyleSpan(TypefaceStyle.Bold), 0, medicineReminder.Medicine.Name.Length, SpanTypes.InclusiveInclusive); formattedText.SetSpan(new AbsoluteSizeSpan(18.ConvertToPixel(activity)), 0, medicineReminder.Medicine.Name.Length, SpanTypes.InclusiveInclusive); formattedText.SetSpan(new StyleSpan(TypefaceStyle.Normal), medicineReminder.Medicine.Name.Length, totalText.Length, SpanTypes.InclusiveInclusive); formattedText.SetSpan(new AbsoluteSizeSpan(14.ConvertToPixel(activity)), medicineReminder.Medicine.Name.Length, totalText.Length, SpanTypes.InclusiveInclusive); medicineName.TextFormatted = formattedText; if (medicineReminder.Reminder != null) { var localizedList = medicineReminder.Reminder.Days.Select(x => x.ToString().ToLower().Translate(activity)).ToList(); var reminderDays = String.Join(", ", localizedList); var frequencies = $" {activity.Resources.GetString(Resource.String.general_view_timeprefix)} {String.Join(" ", medicineReminder.Reminder.FrequencyPerDay)}"; var formattedReminderText = new SpannableStringBuilder(reminderDays + frequencies); formattedReminderText.SetSpan(new ForegroundColorSpan(Color.ParseColor("#121212")), 0, frequencies.Length, SpanTypes.InclusiveInclusive); reminderDetails.TextFormatted = formattedReminderText; } } }
/// <summary> /// Handles IMG tags /// </summary> /// <returns>The image.</returns> /// <param name="text">Text.</param> /// <param name="attributes">Attributes.</param> /// <param name="img">Image.</param> static void startImg(SpannableStringBuilder text, IAttributes attributes, Html.IImageGetter img) { var src = attributes.GetValue("src"); Drawable d = null; if (img != null) { d = img.GetDrawable(src); } if (d == null) { throw new NotImplementedException("Missing Inline image implementation"); // d = Resources.System.GetDrawable (); // getDrawable(com.android.internal.R.drawable.unknown_image); // d.SetBounds (0, 0, d.IntrinsicWidth, d.IntrinsicHeight); } int len = text.Length(); text.Append("\uFFFC"); text.SetSpan(new ImageSpan(d, src), len, text.Length(), SpanTypes.ExclusiveExclusive); }
private void DrawTags() { String tagName; var tagNameList = new List <String> (); if (tagNames.Count == 0) { EditText.Text = String.Empty; return; } foreach (var tagText in tagNames) { tagName = tagText.Length > TagMaxLength?tagText.Substring(0, TagMaxLength - 1).Trim() + "…" : tagText; if (tagText.Length > 0) { tagNameList.Add(tagName); } } // The extra whitespace prevents the ImageSpans and the text they are over // to break at different positions, leaving zero linespacing on edge cases. var tags = new SpannableStringBuilder(String.Join(" ", tagNameList) + " "); int x = 0; foreach (String tagText in tagNameList) { tags.SetSpan(new ImageSpan(MakeTagChip(tagText)), x, x + tagText.Length, SpanTypes.ExclusiveExclusive); x = x + tagText.Length + 1; } EditText.SetText(tags, EditText.BufferType.Spannable); }
private static ISpanned RemoveLastChar(ICharSequence text) { var builder = new SpannableStringBuilder(text); builder.Delete(text.Length() - 1, text.Length()); return(builder); }
public ICharSequence FilterFormatted(ICharSequence source, int start, int end, ISpanned dest, int dstart, int dend) { if (source is SpannableStringBuilder) { var sourceAsSpannableBuilder = (SpannableStringBuilder)source; for (var i = end - 1; i >= start; i--) { if (!isCharacterOk(source.CharAt(i))) { sourceAsSpannableBuilder.Delete(i, i + 1); } } return(sourceAsSpannableBuilder); } else { var filteredStringBuilder = new SpannableStringBuilder(); for (int i = start; i < end; i++) { var currentChar = source.CharAt(i); if (isCharacterOk(currentChar)) { filteredStringBuilder.Append(currentChar); } } return(filteredStringBuilder); } }
protected ISpanned RemoveLastChar(ISpanned text) { var builder = new SpannableStringBuilder(text); builder.Delete(text.Length() - 1, text.Length()); return(builder); }
private void SetSpannableString(TextView _textview, string _label, string _boldText) { SpannableStringBuilder str = new SpannableStringBuilder(_label + _boldText); str.SetSpan(new StyleSpan(TypefaceStyle.Bold), _label.Length, _label.Length + _boldText.Length, SpanTypes.ExclusiveExclusive); _textview.TextFormatted = str; }
private static bool HasAnimatedSpans(SpannableStringBuilder spannableBuilder) { CustomTypefaceSpan[] spans = spannableBuilder.GetSpans(0, spannableBuilder.Length(), Class.FromType(typeof(CustomTypefaceSpan))).Cast<CustomTypefaceSpan>().ToArray(); return spans.Any(span => span.Animated); }
private void ShowMore() { SpannableStringBuilder builder = new SpannableStringBuilder(mFullText + " " + LESS); builder.SetSpan(new LessClickableSpan(this), builder.Length() - LESS.Length, builder.Length(), 0); SetText(builder, BufferType.Spannable); }
public static ICharSequence Parse( Context context, List<IconFontDescriptorWrapper> iconFontDescriptors, string text, TextView target) { context = context.ApplicationContext; // Analyse the text and replace {} blocks with the appropriate character // Retain all transformations in the accumulator SpannableStringBuilder spannableBuilder = new SpannableStringBuilder(text); RecursivePrepareSpannableIndexes(context, text, spannableBuilder, iconFontDescriptors, 0); bool isAnimated = HasAnimatedSpans(spannableBuilder); if (isAnimated) { if (target == null) throw new IllegalArgumentException("You can't use \"spin\" without providing the target TextView."); if (!(target is IHasOnViewAttachListener)) throw new IllegalArgumentException(target.GetType().Name + " does not implement " + "HasOnViewAttachListener. Please use IconTextView, IconButton or IconToggleButton."); bool isAttached = false; var listener = new OnViewAttachListener(); listener.Attach += (s, e) => { isAttached = true; Runnable runnable = null; runnable = new Runnable(() => { if (isAttached) { target.Invalidate(); ViewCompat.PostOnAnimation(target, runnable); } }); ViewCompat.PostOnAnimation(target, runnable); }; listener.Detach += (s, e) => isAttached = false; ((IHasOnViewAttachListener)target).SetOnViewAttachListener(listener); } else { (target as IHasOnViewAttachListener)?.SetOnViewAttachListener(null); } return spannableBuilder; }
protected override void OnCreate(Bundle bundle) { try { RequestWindowFeature(WindowFeatures.NoTitle); base.OnCreate(bundle); LoggerMobile.Instance.logMessage("Opening GamesActivity", LoggerEnum.message); SetContentView(Resource.Layout.PublicGames); LegacyBar = FindViewById<LegacyBar.Library.Bar.LegacyBar>(Resource.Id.actionbar); LegacyBar.SeparatorColor = Color.Purple; AddHomeAction(typeof(Main), Resource.Drawable.icon); // Get our button from the layout resource, // and attach an event to it LegacyBar.ProgressBarVisibility = ViewStates.Visible; //currentGamesList = FindViewById<ListView>(Resource.Id.currentGamesList); pastGamesList = FindViewById<ListView>(Resource.Id.pastGamesList); LegacyBarAction loginAction = new RefreshAction(this, null, Resource.Drawable.ic_action_refresh, this); LegacyBar.AddAction(loginAction); initialPastArray = new GamesJson(); //initialCurrentArray = new GamesJson(); Action pullMorePast = new Action(PullMorePast); //Action pullCurrent = new Action(PullMorePast); PastGamesAdapter = new GamesAdapter(this, initialPastArray.Games, pullMorePast); //CurrentGamesAdapter = new GamesAdapter(this, initialCurrentArray.Games, null); //currentGamesList.Adapter = CurrentGamesAdapter; pastGamesList.Adapter = PastGamesAdapter; Game.PullCurrentGames(this, UpdateCurrentAdapter); Game.PullPastGames(PAGE_COUNT, lastPagePulled, this, UpdatePastAdapter); //currentGamesList.ItemClick += currentGamesList_ItemClick; pastGamesList.ItemClick += pastGamesList_ItemClick; var myString = new SpannableStringBuilder("lol"); Selection.SelectAll(myString); // needs selection or Index Out of bounds LegacyBarAction infoAction = new DefaultLegacyBarAction(this, CreateInfoIntent(), Resource.Drawable.action_about); LegacyBar.AddAction(infoAction); m_AdView = FindViewById(Resource.Id.adView); if (SettingsMobile.Instance.User != null && SettingsMobile.Instance.User.IsValidSub) { } } catch (Exception exception) { ErrorHandler.Save(exception, MobileTypeEnum.Android, (Context)this); } }
private static Boolean HasAnimatedSpans(SpannableStringBuilder spannableBuilder) { var spans = spannableBuilder.GetSpans(0, spannableBuilder.Length(), Java.Lang.Class.FromType(typeof(CustomTypefaceSpan))); foreach (var span in spans) { if (span is CustomTypefaceSpan) { if (((CustomTypefaceSpan)span).IsAnimated) return true; } } return false; }
private void UpdateTabIcons() { var tabLayout = this.tabLayout; if (tabLayout.TabCount != this.Element.Children.Count) return; for (int i = 0; i < this.Element.Children.Count; ++i) { var page = this.Element.Children[i]; if (string.IsNullOrEmpty(page.Icon)) { var glyph = (string)page.GetValue(AttachedFontIcon.GlyphProperty); if (!string.IsNullOrWhiteSpace(glyph)) { SpannableStringBuilder sb = new SpannableStringBuilder(); sb.Append(glyph); var font = (string)page.GetValue(AttachedFontIcon.FontFamilyProperty); if (!string.IsNullOrWhiteSpace(font)) { var span = new CustomTypefaceSpan(font); sb.SetSpan(span, 0, glyph.Length, SpanTypes.ExclusiveExclusive); } //var size = (int)(double)page.GetValue(AttachedFontIcon.FontSizeProperty); sb.SetSpan(new AbsoluteSizeSpan(40), 0, glyph.Length, SpanTypes.ExclusiveExclusive); sb.Append("\n"); sb.Append(page.Title); //sb.SetSpan(new ForegroundColorSpan(Android.Graphics.Color.Red), 3, 4, SpanTypes.ExclusiveExclusive); //Must set app:tabTextAppearance textAllCaps to false. // See : tabs.xml, //if not do this, span will not work not work tabLayout.GetTabAt(i).SetText(sb); ////without specify color //var v = new TextView(this.Context) { // TextAlignment = Android.Views.TextAlignment.Center //}; //v.SetText(sb, TextView.BufferType.Spannable); //tabLayout.GetTabAt(i).SetCustomView(v); } } } }
private void DrawTags () { String tagName; var tagNameList = new List<String> (); if (tagNames.Count == 0) { EditText.Text = String.Empty; return; } foreach (var tagText in tagNames) { tagName = tagText.Length > TagMaxLength ? tagText.Substring (0, TagMaxLength - 1).Trim () + "…" : tagText; if (tagText.Length > 0) { tagNameList.Add (tagName); } } // The extra whitespace prevents the ImageSpans and the text they are over // to break at different positions, leaving zero linespacing on edge cases. var tags = new SpannableStringBuilder (String.Join (" ", tagNameList) + " "); int x = 0; foreach (String tagText in tagNameList) { tags.SetSpan (new ImageSpan (MakeTagChip (tagText)), x, x + tagText.Length, SpanTypes.ExclusiveExclusive); x = x + tagText.Length + 1; } EditText.SetText (tags, EditText.BufferType.Spannable); }
private void AppendColored (SpannableStringBuilder builder, string text, int colorResId) { builder.Append (text); builder.SetSpan (new ForegroundColorSpan (Resources.GetColor (colorResId)), builder.Length () - text.Length, builder.Length (), 0); }
public override void OnMessageReceived (IMessageEvent messageEvent) { string path = messageEvent.Path; if (path.Equals (Constants.QUIZ_EXITED_PATH)) { ((NotificationManager)GetSystemService (NotificationService)).CancelAll (); } if (path.Equals (Constants.QUIZ_ENDED_PATH) || path.Equals (Constants.QUIZ_EXITED_PATH)) { var dataMap = DataMap.FromByteArray (messageEvent.GetData ()); int numCorrect = dataMap.GetInt (Constants.NUM_CORRECT); int numIncorrect = dataMap.GetInt (Constants.NUM_INCORRECT); int numSkipped = dataMap.GetInt (Constants.NUM_SKIPPED); var builder = new Notification.Builder (this) .SetContentTitle (GetString (Resource.String.quiz_report)) .SetSmallIcon (Resource.Drawable.ic_launcher) .SetLocalOnly (true); var quizReportText = new SpannableStringBuilder (); AppendColored (quizReportText, numCorrect.ToString (), Resource.Color.dark_green); quizReportText.Append (" " + GetString (Resource.String.correct) + "\n"); AppendColored (quizReportText, numIncorrect.ToString (), Resource.Color.dark_red); quizReportText.Append (" " + GetString (Resource.String.incorrect) + "\n"); AppendColored (quizReportText, numSkipped.ToString (), Resource.Color.dark_yellow); quizReportText.Append (" " + GetString (Resource.String.skipped) + "\n"); builder.SetContentText (quizReportText); if (!path.Equals (Constants.QUIZ_EXITED_PATH)) { builder.AddAction (Resource.Drawable.ic_launcher, GetString (Resource.String.reset_quiz), GetResetQuizPendingIntent ()); } ((NotificationManager)GetSystemService (NotificationService)) .Notify (QUIZ_REPORT_NOTIF_ID, builder.Build ()); } }
public static void Linkify(Activity activity, TextView textView, string linkText, string url) { var text = textView.Text; var builder = new SpannableStringBuilder(); builder.Append(text); builder.SetSpan(new MyClickableSpan(v => ShowWebPage(activity, url)), text.IndexOf(linkText), text.IndexOf(linkText) + linkText.Length, SpanTypes.ExclusiveExclusive ); textView.MovementMethod = LinkMovementMethod.Instance; }
private static void RecursivePrepareSpannableIndexes(Context context, String text, SpannableStringBuilder builder, IList<IIconModule> modules, Int32 start) { // Try to find a {...} in the string and extract expression from it var stringText = builder.ToString(); var startIndex = stringText.IndexOf("{", start, StringComparison.Ordinal); if (startIndex == -1) return; var endIndex = stringText.IndexOf("}", startIndex, StringComparison.Ordinal) + 1; var expression = stringText.Substring(startIndex + 1, endIndex - 2); // Split the expression and retrieve the icon key var strokes = expression.Split(' '); var key = strokes[0]; // Loop through the descriptors to find a key match IIconModule module = null; IIcon icon = null; for (var i = 0; i < modules.Count; i++) { module = modules[i]; icon = module.GetIcon(key); if (icon != null) break; } // If no match, ignore and continue if (icon == null) { RecursivePrepareSpannableIndexes(context, text, builder, modules, endIndex); return; } // See if any more stroke within {} should be applied var iconSizePx = -1f; var iconColor = Int32.MaxValue; var iconSizeRatio = -1f; var spin = false; var baselineAligned = false; for (var i = 1; i < strokes.Length; i++) { var stroke = strokes[i]; // Look for "spin" if (stroke.Equals("spin", StringComparison.OrdinalIgnoreCase)) { spin = true; } // Look for "baseline" else if (stroke.Equals("baseline", StringComparison.OrdinalIgnoreCase)) { baselineAligned = true; } // Look for an icon size else if (Regex.IsMatch(stroke, "([0-9]*(\\.[0-9]*)?)dp")) { iconSizePx = dpToPx(context, Convert.ToSingle(stroke.Substring(0, stroke.Length - 2))); } else if (Regex.IsMatch(stroke, "([0-9]*(\\.[0-9]*)?)sp")) { iconSizePx = spToPx(context, Convert.ToSingle(stroke.Substring(0, stroke.Length - 2))); } else if (Regex.IsMatch(stroke, "([0-9]*)px")) { iconSizePx = Convert.ToInt32(stroke.Substring(0, stroke.Length - 2)); } else if (Regex.IsMatch(stroke, "@dimen/(.*)")) { iconSizePx = GetPxFromDimen(context, context.PackageName, stroke.Substring(7)); if (iconSizePx < 0) throw new ArgumentException("Unknown resource " + stroke + " in \"" + text + "\""); } else if (Regex.IsMatch(stroke, "@android:dimen/(.*)")) { iconSizePx = GetPxFromDimen(context, ANDROID_PACKAGE_NAME, stroke.Substring(15)); if (iconSizePx < 0) throw new ArgumentException("Unknown resource " + stroke + " in \"" + text + "\""); } else if (Regex.IsMatch(stroke, "([0-9]*(\\.[0-9]*)?)%")) { iconSizeRatio = Convert.ToSingle(stroke.Substring(0, stroke.Length - 1)) / 100f; } // Look for an icon color else if (Regex.IsMatch(stroke, "#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})")) { iconColor = Color.ParseColor(stroke); } else if (Regex.IsMatch(stroke, "@color/(.*)")) { iconColor = GetColorFromResource(context, context.PackageName, stroke.Substring(7)); if (iconColor == Int32.MaxValue) throw new ArgumentException("Unknown resource " + stroke + " in \"" + text + "\""); } else if (Regex.IsMatch(stroke, "@android:color/(.*)")) { iconColor = GetColorFromResource(context, ANDROID_PACKAGE_NAME, stroke.Substring(15)); if (iconColor == Int32.MaxValue) throw new ArgumentException("Unknown resource " + stroke + " in \"" + text + "\""); } else { throw new ArgumentException("Unknown expression " + stroke + " in \"" + text + "\""); } } // Replace the character and apply the typeface builder = (SpannableStringBuilder)builder.Replace(startIndex, endIndex, "" + icon.Character); builder.SetSpan(new CustomTypefaceSpan(icon, module.GetTypeface(context), iconSizePx, iconSizeRatio, iconColor, spin, baselineAligned), startIndex, startIndex + 1, SpanTypes.InclusiveExclusive); RecursivePrepareSpannableIndexes(context, text, builder, modules, startIndex); }
protected override void OnCreate(Bundle bundle) { try { RequestWindowFeature(WindowFeatures.NoTitle); base.OnCreate(bundle); LoggerMobile.Instance.logMessage("Opening LeaguesActibity", LoggerEnum.message); SetContentView(Resource.Layout.PublicLeagues); LegacyBar = FindViewById<LegacyBar.Library.Bar.LegacyBar>(Resource.Id.actionbar); LegacyBar.SetHomeLogo(Resource.Drawable.icon); LegacyBar.SeparatorColor = Color.Purple; LegacyBarAction azAction = new MenuAction(this, null, Resource.Drawable.a_z); LegacyBar.AddAction(azAction); LegacyBar = FindViewById<LegacyBar.Library.Bar.LegacyBar>(Resource.Id.actionbar); AddHomeAction(typeof(Main), Resource.Drawable.icon); // Get our button from the layout resource, // and attach an event to it Action<LeaguesJson> leagues = new Action<LeaguesJson>(UpdateAdapter); LegacyBar.ProgressBarVisibility = ViewStates.Visible; League.PullLeagues(lastPagePulled, PAGE_COUNT, "", (Context)this, leagues); skaterList = FindViewById<ListView>(Resource.Id.leagueList); initialArray = new LeaguesJson(); Action pullMore= new Action(PullMore); ListAdapter = new LeagueAdapter(this, initialArray.Leagues, pullMore); skaterList.Adapter = ListAdapter; skaterList.FastScrollEnabled = true; skaterList.ItemClick += skaterList_ItemClick; var myString = new SpannableStringBuilder("lol"); Selection.SelectAll(myString); // needs selection or Index Out of bounds _dialog = new MyCharacterPickerDialog(this, new View(this), myString, options, false); _dialog.Clicked += (sender, args) => { lastPagePulled = 0; lastLetterPulled = args.Text; LegacyBar.ProgressBarVisibility = ViewStates.Visible; League.PullLeagues(0, PAGE_COUNT, lastLetterPulled, (Context)this, leagues); initialArray.Leagues.Clear(); }; search_leagues = FindViewById<EditText>(Resource.Id.search_leagues); search_leagues.TextChanged += search_skaters_TextChanged; var searchMenuItemAction = new SearchAction(this, null, Resource.Drawable.ic_action_search, search_leagues); LegacyBar.AddAction(searchMenuItemAction); LegacyBarAction infoAction = new DefaultLegacyBarAction(this, CreateInfoIntent(), Resource.Drawable.action_about); LegacyBar.AddAction(infoAction); m_AdView = FindViewById(Resource.Id.adView); if (SettingsMobile.Instance.User != null && SettingsMobile.Instance.User.IsValidSub) { } } catch (Exception exception) { ErrorHandler.Save(exception, MobileTypeEnum.Android, (Context)this); } }
protected override void OnCreate(Bundle bundle) { try { RequestWindowFeature(WindowFeatures.NoTitle); base.OnCreate(bundle); LoggerMobile.Instance.logMessage("Opening EventsActivity", LoggerEnum.message); SetContentView(Resource.Layout.PublicEvents); LegacyBar = FindViewById<LegacyBar.Library.Bar.LegacyBar>(Resource.Id.actionbar); LegacyBar.SetHomeLogo(Resource.Drawable.icon); LegacyBar.SeparatorColor = Color.Purple; LegacyBar = FindViewById<LegacyBar.Library.Bar.LegacyBar>(Resource.Id.actionbar); AddHomeAction(typeof(Main), Resource.Drawable.icon); // Get our button from the layout resource, // and attach an event to it Action<EventsJson> evs = new Action<EventsJson>(UpdateAdapter); LegacyBar.ProgressBarVisibility = ViewStates.Visible; eventsList = FindViewById<ListView>(Resource.Id.eventsList); initialArray = new EventsJson(); Action pullMore = new Action(PullMore); RDNation.Droid.Classes.Public.Calendar.PullEvents(lastPagePulled, PAGE_COUNT, (Context)this, evs); ListAdapter = new EventsAdapter(this, initialArray.Events, pullMore); eventsList.Adapter = ListAdapter; eventsList.FastScrollEnabled = true; eventsList.ItemClick += skaterList_ItemClick; var myString = new SpannableStringBuilder("lol"); Selection.SelectAll(myString); // needs selection or Index Out of bounds search_events = FindViewById<EditText>(Resource.Id.search_events); search_events.TextChanged += search_skaters_TextChanged; var searchMenuItemAction = new SearchAction(this, null, Resource.Drawable.ic_action_search, search_events); LegacyBar.AddAction(searchMenuItemAction); InitializeLocationManager(); LegacyBarAction infoAction = new DefaultLegacyBarAction(this, CreateInfoIntent(), Resource.Drawable.action_about); LegacyBar.AddAction(infoAction); m_AdView = FindViewById(Resource.Id.adView); if (SettingsMobile.Instance.User != null && SettingsMobile.Instance.User.IsValidSub) { } } catch (Exception exception) { ErrorHandler.Save(exception, MobileTypeEnum.Android, (Context)this); } }
private static void RecursivePrepareSpannableIndexes(Context context, string fullText, SpannableStringBuilder text, IList<IconFontDescriptorWrapper> iconFontDescriptors, int start) { // Try to find a {...} in the string and extract expression from it var stringText = text.ToString(); var startIndex = stringText.IndexOf("{", start, StringComparison.Ordinal); if (startIndex == -1) { return; } var endIndex = stringText.IndexOf("}", startIndex, StringComparison.Ordinal) + 1; var expression = stringText.Substring(startIndex + 1, endIndex - 1 - (startIndex + 1)); // Split the expression and retrieve the icon key var strokes = expression.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); var key = strokes[0]; // Loop through the descriptors to find a key match IconFontDescriptorWrapper iconFontDescriptor = null; Icon? icon = null; for (var i = 0; i < iconFontDescriptors.Count; i++) { iconFontDescriptor = iconFontDescriptors[i]; icon = iconFontDescriptor.GetIcon(key); if (icon.HasValue) { break; } } // If no match, ignore and continue if (!icon.HasValue) { RecursivePrepareSpannableIndexes(context, fullText, text, iconFontDescriptors, endIndex); return; } // See if any more stroke within {} should be applied float iconSizePx = -1; var iconColor = int.MaxValue; float iconSizeRatio = -1; var spin = false; for (var i = 1; i < strokes.Length; i++) { var stroke = strokes[i]; // Look for "spin" if (stroke.Equals("spin", StringComparison.CurrentCultureIgnoreCase)) { spin = true; } // Look for an icon size else if (stroke.Matches("([0-9]*(\\.[0-9]*)?)dp")) { iconSizePx = DpToPx(context, Convert.ToSingle(stroke.Substring(0, stroke.Length - 2))); } else if (stroke.Matches("([0-9]*(\\.[0-9]*)?)sp")) { iconSizePx = SpToPx(context, Convert.ToSingle(stroke.Substring(0, stroke.Length - 2))); } else if (stroke.Matches("([0-9]*)px")) { iconSizePx = Convert.ToInt32(stroke.Substring(0, stroke.Length - 2)); } else if (stroke.Matches("@dimen/(.*)")) { iconSizePx = GetPxFromDimen(context, stroke.Substring(7)); if (iconSizePx < 0) { throw new ArgumentException("Unknown resource " + stroke + " in \"" + fullText + "\""); } } else if (stroke.Matches("([0-9]*(\\.[0-9]*)?)%")) { iconSizeRatio = Convert.ToSingle(stroke.Substring(0, stroke.Length - 1))/100f; } // Look for an icon WithColor else if (stroke.Matches("#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})")) { iconColor = Color.ParseColor(stroke); } else if (stroke.Matches("@WithColor/(.*)")) { iconColor = GetColorFromResource(context, stroke.Substring(7)); if (iconColor == int.MaxValue) { throw new ArgumentException("Unknown resource " + stroke + " in \"" + fullText + "\""); } } else { throw new ArgumentException("Unknown expression " + stroke + " in \"" + fullText + "\""); } } // Replace the character and apply the typeface text.Replace(startIndex, endIndex, "" + icon.Value.Character); text.SetSpan( new CustomTypefaceSpan(icon.Value, iconFontDescriptor.GetTypeface(context), iconSizePx, iconSizeRatio, iconColor, spin), startIndex, startIndex + 1, SpanTypes.InclusiveExclusive); RecursivePrepareSpannableIndexes(context, fullText, text, iconFontDescriptors, startIndex); }
/** * Handle {@link SessionsQuery} {@link Cursor}. */ private void OnSessionQueryComplete (ICursor cursor) { try { mSessionCursor = true; if (!cursor.MoveToFirst ()) { return; } // Format time block this session occupies long blockStart = cursor.GetLong (SessionsQuery.BLOCK_START); long blockEnd = cursor.GetLong (SessionsQuery.BLOCK_END); String roomName = cursor.GetString (SessionsQuery.ROOM_NAME); String subtitle = UIUtils.FormatSessionSubtitle (blockStart, blockEnd, roomName, Activity); mTitleString = cursor.GetString (SessionsQuery.TITLE); mTitle.Text = mTitleString; mSubtitle.Text = subtitle; mUrl = cursor.GetString (SessionsQuery.URL); if (TextUtils.IsEmpty (mUrl)) { mUrl = ""; } mHashtag = cursor.GetString (SessionsQuery.HASHTAG); mTagDisplay = mRootView.FindViewById<TextView> (Resource.Id.session_tags_button); if (!TextUtils.IsEmpty (mHashtag)) { // Create the button text SpannableStringBuilder sb = new SpannableStringBuilder (); sb.Append (GetString (Resource.String.tag_stream) + " "); int boldStart = sb.Length (); sb.Append (GetHashtagsString ()); sb.SetSpan (sBoldSpan, boldStart, sb.Length (), SpanTypes.ExclusiveExclusive); mTagDisplay.Text = (string)sb; mTagDisplay.Click += (sender, e) => { Intent intent = new Intent (Activity, typeof(TagStreamActivity)); intent.PutExtra (TagStreamFragment.EXTRA_QUERY, GetHashtagsString ()); StartActivity (intent); }; } else { mTagDisplay.Visibility = ViewStates.Gone; } mRoomId = cursor.GetString (SessionsQuery.ROOM_ID); // Unregister around setting checked state to avoid triggering // listener since change isn't user generated. mStarred.CheckedChange += null; mStarred.Checked = cursor.GetInt (SessionsQuery.STARRED) != 0; mStarred.CheckedChange += HandleCheckedChange; String sessionAbstract = cursor.GetString (SessionsQuery.ABSTRACT); if (!TextUtils.IsEmpty (sessionAbstract)) { UIUtils.SetTextMaybeHtml (mAbstract, sessionAbstract); mAbstract.Visibility = ViewStates.Visible; mHasSummaryContent = true; } else { mAbstract.Visibility = ViewStates.Gone; } View requirementsBlock = mRootView.FindViewById (Resource.Id.session_requirements_block); String sessionRequirements = cursor.GetString (SessionsQuery.REQUIREMENTS); if (!TextUtils.IsEmpty (sessionRequirements)) { UIUtils.SetTextMaybeHtml (mRequirements, sessionRequirements); requirementsBlock.Visibility = ViewStates.Visible; mHasSummaryContent = true; } else { requirementsBlock.Visibility = ViewStates.Gone; } // Show empty message when all data is loaded, and nothing to show if (mSpeakersCursor && !mHasSummaryContent) { mRootView.FindViewWithTag (Android.Resource.Id.Empty).Visibility = ViewStates.Visible; } //AnalyticsUtils.getInstance(getActivity()).trackPageView("/Sessions/" + mTitleString); UpdateLinksTab (cursor); UpdateNotesTab (); } finally { cursor.Close (); } }
private static bool HasAnimatedSpans(SpannableStringBuilder spannableBuilder) { var spans = spannableBuilder.GetSpans(0, spannableBuilder.Length(), Class.FromType(typeof (CustomTypefaceSpan))); return spans.OfType<CustomTypefaceSpan>().Any(customTypefaceSpan => customTypefaceSpan.Animated); }
//Java.Lang.Object.Locale localinfo; public override View GetSampleContent (Context con) { Context localcontext = con; int width = con.Resources.DisplayMetrics.WidthPixels -40; FrameLayout frameLayout = new FrameLayout(con); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent, GravityFlags.FillVertical); frameLayout.LayoutParameters = layoutParams; LinearLayout layout=new LinearLayout(con); layout.LayoutParameters=new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); layout.SetGravity(GravityFlags.FillVertical); layout.Orientation=Orientation.Vertical; TextView dummy0 = new TextView(con); dummy0.Text="Simple Interest Calculator"; dummy0.Gravity=GravityFlags.Center; dummy0.TextSize=24; layout.AddView(dummy0); TextView dummy7 = new TextView(con); layout.AddView(dummy7); TextView dummy = new TextView(con); dummy.Text="The formula for finding simple interest is:"; dummy.TextSize=18; layout.AddView(dummy); layout.FocusableInTouchMode=true; SpannableStringBuilder builder = new SpannableStringBuilder(); TextView dummy1 = new TextView(con); String str= "Interest"; SpannableString strSpannable= new SpannableString(str); strSpannable.SetSpan(new ForegroundColorSpan(Color.ParseColor("#66BB6A")), 0, str.Length, 0); builder.Append(strSpannable); builder.Append(" = Principal * Rate * Time"); dummy1.SetText(builder, TextView.BufferType.Spannable); dummy1.TextSize=18; layout.AddView(dummy1); TextView dummy8 = new TextView(con); layout.AddView(dummy8); /* Principal amount Stack */ LinearLayout principalStack = new LinearLayout(con); TextView txtPricipal = new TextView(con); txtPricipal.LayoutParameters=new ViewGroup.LayoutParams(width / 2, 100); txtPricipal.Text="Principal"; principalamount =new SfNumericTextBox(con); principalamount.FormatString="C"; principalamount.LayoutParameters=new ViewGroup.LayoutParams(width / 2, 100); principalamount.Value=1000; principalamount.AllowNull = true; principalamount.Watermark = "Principal Amount"; principalamount.MaximumNumberDecimalDigits=2; var culture = new Java.Util.Locale("en","US"); principalamount.CultureInfo = culture; principalamount.ValueChangeMode=ValueChangeMode.OnKeyFocus; principalStack.Orientation = Orientation.Horizontal; principalStack.AddView(txtPricipal); principalStack.AddView(principalamount); layout.AddView(principalStack); TextView dummy3 = new TextView(con); layout.AddView(dummy3); /* Interest Input Box */ LinearLayout InterestcalStack = new LinearLayout(con); TextView txtInterest = new TextView(con); txtInterest.LayoutParameters=new ViewGroup.LayoutParams(width / 2, 100); txtInterest.Text="Interest Rate"; Interestvalue =new SfNumericTextBox(con); Interestvalue.FormatString="P"; Interestvalue.PercentDisplayMode=PercentDisplayMode.Compute; Interestvalue.MaximumNumberDecimalDigits=2; Interestvalue.ValueChangeMode=ValueChangeMode.OnKeyFocus; Interestvalue.LayoutParameters=new ViewGroup.LayoutParams(width / 2, 100); Interestvalue.Value=0.1f; Interestvalue.Watermark = "Rate of Interest"; Interestvalue.AllowNull = true; Interestvalue.CultureInfo = culture; InterestcalStack.Orientation=Orientation.Horizontal; InterestcalStack.AddView(txtInterest); InterestcalStack.AddView(Interestvalue); layout.AddView(InterestcalStack); TextView dummy2 = new TextView(con); layout.AddView(dummy2); /* Period Input TextBox */ LinearLayout periodStack = new LinearLayout(con); TextView period = new TextView(con); period.LayoutParameters=new ViewGroup.LayoutParams(width / 2, 100); period.Text="Term"; periodValue =new SfNumericTextBox(con); periodValue.FormatString=" years"; periodValue.MaximumNumberDecimalDigits=0; periodValue.LayoutParameters=new ViewGroup.LayoutParams(width / 2, 100); periodValue.Value=20; periodValue.Watermark = "Period (in years)"; periodValue.ValueChangeMode=ValueChangeMode.OnKeyFocus; periodValue.CultureInfo = culture; periodValue.AllowNull = true; periodStack.Orientation=Orientation.Horizontal; periodStack.AddView(period); periodStack.AddView(periodValue); layout.AddView(periodStack); /* OutPut values */ LinearLayout outputStack = new LinearLayout(con); TextView outputtxt = new TextView(con); outputtxt.LayoutParameters=new ViewGroup.LayoutParams(width / 2, 100); outputtxt.Text="Interest"; outputtxt.SetTextColor(Color.ParseColor("#66BB6A")); OutputNumbertxtBox =new SfNumericTextBox(con); OutputNumbertxtBox.FormatString="c"; OutputNumbertxtBox.MaximumNumberDecimalDigits=0; OutputNumbertxtBox.AllowNull=true; OutputNumbertxtBox.CultureInfo = culture; OutputNumbertxtBox.Watermark="Enter Values"; OutputNumbertxtBox.Clickable=false; OutputNumbertxtBox.Value = (float)(1000 * 0.1 * 20); OutputNumbertxtBox.Enabled=false; OutputNumbertxtBox.LayoutParameters=new ViewGroup.LayoutParams(width / 2, 100); OutputNumbertxtBox.ValueChangeMode=ValueChangeMode.OnLostFocus; outputStack.Orientation=Orientation.Horizontal; outputStack.AddView(outputtxt); outputStack.AddView(OutputNumbertxtBox); layout.AddView(outputStack); TextView dummy4 = new TextView(con); layout.SetPadding(20, 20, 10, 20); layout.AddView(dummy4); principalamount.ValueChanged+= (object sender, SfNumericTextBox.ValueChangedEventArgs e) => { if(!e.P1.ToString().Equals("")&&!periodValue.Value.ToString().Equals("")&&!Interestvalue.Value.ToString().Equals("")) OutputNumbertxtBox.Value=e.P1 * periodValue.Value * Interestvalue.Value; }; periodValue.ValueChanged+= (object sender, SfNumericTextBox.ValueChangedEventArgs e) => { if(!e.P1.ToString().Equals("")&&!principalamount.Value.ToString().Equals("")&&!Interestvalue.Value.ToString().Equals("")) OutputNumbertxtBox.Value=e.P1* principalamount.Value*Interestvalue.Value; }; Interestvalue.ValueChanged+= (object sender, SfNumericTextBox.ValueChangedEventArgs e) => { if(!e.P1.ToString().Equals("")&&!principalamount.Value.ToString().Equals("")&&!periodValue.Value.ToString().Equals("")) OutputNumbertxtBox.Value=e.P1 * principalamount.Value * periodValue.Value; }; layout.Touch+= (object sender, View.TouchEventArgs e) => { if(OutputNumbertxtBox.IsFocused || Interestvalue.IsFocused ||periodValue.IsFocused || principalamount.IsFocused){ Rect outRect = new Rect(); OutputNumbertxtBox.GetGlobalVisibleRect(outRect); Interestvalue.GetGlobalVisibleRect(outRect); periodValue.GetGlobalVisibleRect(outRect); principalamount.GetGlobalVisibleRect(outRect); if (!outRect.Contains((int)e.Event.RawX, (int)e.Event.RawY)) { if(!OutputNumbertxtBox.Value.ToString().Equals("")) OutputNumbertxtBox.ClearFocus(); if(!Interestvalue.Value.ToString().Equals("")) Interestvalue.ClearFocus(); if(!periodValue.Value.ToString().Equals("")) periodValue.ClearFocus(); if(!principalamount.Value.ToString().Equals("")) principalamount.ClearFocus(); } hideSoftKeyboard((Activity)localcontext); } }; frameLayout.AddView(layout); ScrollView scrollView = new ScrollView(con); scrollView.AddView(frameLayout); return scrollView; }
public void FillImagePost(PostImageViewHolder vh,int position){ try{ vh.AuthorName.Text = _Posts[position].AuthorName; var context = Android.App.Application.Context; vh.HeaderRating.Text = _Posts [position].Rating.ToString (); vh.BottomRating.Text = _Posts [position].Rating.ToString (); if (_Posts [position].Rating > 0) { vh.HeaderRating.SetTextColor (context.Resources.GetColor(Resource.Color.mainGreen)); vh.BottomRating.SetTextColor (context.Resources.GetColor(Resource.Color.mainGreen)); var text = " + "+_Posts[position].Rating; vh.HeaderRating.Text = text; vh.BottomRating.Text = text; } if (_Posts [position].Rating < 0) { vh.HeaderRating.SetTextColor (context.Resources.GetColor(Resource.Color.red)); vh.BottomRating.SetTextColor (context.Resources.GetColor(Resource.Color.red)); var text = ""+_Posts[position].Rating; vh.HeaderRating.Text = text; vh.BottomRating.Text = text; } vh.PostTime.Text = _Posts[position].PostTime; vh.Title.Text = _Posts[position].Title; if(_Posts[position].Description!=null && !String.IsNullOrEmpty(_Posts[position].Description.ToString())){ vh.Description.Text = _Posts[position].Description.ToString(); vh.Description.Visibility = ViewStates.Visible; }else{ vh.Description.Text = String.Empty; vh.Description.Visibility = ViewStates.Gone; } // if(_Posts[position].FormattedDescription!=null && _Posts[position].FormattedDescription.Count>0){ // SpannableStringBuilder descriptionBulder = new SpannableStringBuilder(); // Color descTextColorDarkGray = context.Resources.GetColor(Resource.Color.darkGray); // Color descTextColorGray = context.Resources.GetColor(Resource.Color.gray); // // foreach(var des in _Posts[position].FormattedDescription){ // if(des.Item1 == "text"){ // SpannableString tag1 = new SpannableString(des.Item2); // // tag1.SetSpan(new ForegroundColorSpan(descTextColorGray), 0, tag1.Length(), SpanTypes.ExclusiveExclusive); // descriptionBulder.Append(tag1); // } // if(des.Item1 == "textLink"){ // SpannableString tag2 = new SpannableString(des.Item2); // // tag2.SetSpan(new ForegroundColorSpan(descTextColorDarkGray), 0, tag2.Length(), SpanTypes.ExclusiveExclusive); // descriptionBulder.Append(tag2); // } // } // if(descriptionBulder.Count()>0){ // //vh.Description.TextFormatted = descriptionBulder; // vh.Description.SetText(descriptionBulder,TextView.BufferType.Spannable); // } // }else{ // vh.Description.Visibility = ViewStates.Invisible; // vh.Description.Text = null; // } //vh._Description.Text = _Posts[position].Description; //vh._Description.Text = _Posts[position].Description; SpannableStringBuilder stringBuilder = new SpannableStringBuilder(); Color textColor = context.Resources.GetColor(Resource.Color.mainGreen); var tagsBuilder = new StringBuilder(); foreach (var tag in _Posts[position].Tags) { SpannableString tag1 = new SpannableString("#"+tag); tag1.SetSpan(new ForegroundColorSpan(textColor), 0, tag1.Length(), SpanTypes.ExclusiveInclusive); stringBuilder.Append(tag1); stringBuilder.Append(" "); //SpannableString tag2 = new SpannableString(" "); //stringBuilder.Append(tag2); //stringBuilder.SetSpan(new TagSpan(backgroundColor, backgroundColor), stringBuilder.Length() - tag2.Length(), stringBuilder.Length(), SpanTypes.ExclusiveExclusive); //tagsBuilder.Append("#"+tag+" "); } vh.Tags.SetText(stringBuilder,TextView.BufferType.Spannable); //vh.Tags.Text = tagsBuilder.ToString(); //vh.Tags.TextFormatted = stringBuilder; vh.Comments.Text = _Posts[position].Comments.ToString(); vh.Image.Click -= videoHandler; vh.Image.Click -= imageHandler; vh.Image.Click -= gifHandler; if(_Posts[position].PostType==PostType.Video){ if (vh.Image != null) { vh.Image.SetTag (Resource.String.currentPosition, vh.AdapterPosition.ToString ()); vh.Image.SetTag (Resource.String.imageUrl, _Posts [vh.AdapterPosition].VideoUrl); vh.Image.Click -= imageHandler; vh.Image.Click -= gifHandler; vh.Image.Click -= videoHandler; vh.Image.Click += videoHandler; Picasso.With(Android.App.Application.Context) .Load(_Posts[position].Url) .Transform(new CropSquareTransformation()) .Into(vh.Image); } } if(_Posts[position].PostType==PostType.Image){ if (vh.Image != null) { vh.Image.SetTag (Resource.String.currentPosition, vh.AdapterPosition.ToString ()); vh.Image.SetTag (Resource.String.imageUrl, _Posts [vh.AdapterPosition].Url); vh.Image.SetTag (Resource.String.isbiggeravailable,_Posts [vh.AdapterPosition].IsBiggerAvailable); vh.Image.Click -= videoHandler; vh.Image.Click -= gifHandler; vh.Image.Click -= imageHandler; vh.Image.Click += imageHandler; Picasso.With(Android.App.Application.Context) .Load(_Posts[position].Url) .Transform(new CropSquareTransformation()) .Into(vh.Image); } } if(_Posts[position].PostType==PostType.Gif){ if (vh.Image != null) { vh.Image.SetTag (Resource.String.currentPosition, vh.AdapterPosition.ToString ()); vh.Image.SetTag (Resource.String.imageUrl, _Posts [vh.AdapterPosition].GifUrl); vh.Image.Click -= videoHandler; vh.Image.Click -= imageHandler; vh.Image.Click -= gifHandler; vh.Image.Click += gifHandler; Picasso.With(Android.App.Application.Context) .Load(_Posts[position].Url) .Transform(new CropSquareTransformation()) .Into(vh.Image); } } }catch(Exception ex){ Insights.Initialize("0637c26a1b2e27693e05298f7c3c3a04c102a3c7", Application.Context); Insights.Report(ex,new Dictionary<string,string>{{"Message",ex.Message}},Insights.Severity.Error); var text = ex.Message; } }
public void FillMultiImagePost(PostMultiImageViewHolder vh, int position) { try { vh.AuthorName.Text = _Posts[position].AuthorName; var context = Android.App.Application.Context; vh.HeaderRating.Text = _Posts[position].Rating.ToString(); vh.BottomRating.Text = _Posts[position].Rating.ToString(); if (_Posts[position].Rating > 0) { vh.HeaderRating.SetTextColor(context.Resources.GetColor(Resource.Color.mainGreen)); vh.BottomRating.SetTextColor(context.Resources.GetColor(Resource.Color.mainGreen)); var text = " + " + _Posts[position].Rating; vh.HeaderRating.Text = text; vh.BottomRating.Text = text; } if (_Posts[position].Rating < 0) { vh.HeaderRating.SetTextColor(context.Resources.GetColor(Resource.Color.red)); vh.BottomRating.SetTextColor(context.Resources.GetColor(Resource.Color.red)); var text = "" + _Posts[position].Rating; vh.HeaderRating.Text = text; vh.BottomRating.Text = text; } vh.PostTime.Text = _Posts[position].PostTime; vh.Title.Text = _Posts[position].Title; if (_Posts[position].Description != null && !String.IsNullOrEmpty(_Posts[position].Description.ToString())) { vh.Description.Text = _Posts[position].Description.ToString(); vh.Description.Visibility = ViewStates.Visible; } else { vh.Description.Text = String.Empty; vh.Description.Visibility = ViewStates.Gone; } SpannableStringBuilder stringBuilder = new SpannableStringBuilder(); Color textColor = context.Resources.GetColor(Resource.Color.mainGreen); foreach (var tag in _Posts[position].Tags) { SpannableString tag1 = new SpannableString("#" + tag); tag1.SetSpan(new ForegroundColorSpan(textColor), 0, tag1.Length(), SpanTypes.ExclusiveExclusive); stringBuilder.Append(tag1); stringBuilder.Append(" "); //SpannableString tag2 = new SpannableString(" "); //stringBuilder.Append(tag2); //stringBuilder.SetSpan(new TagSpan(backgroundColor, backgroundColor), stringBuilder.Length() - tag2.Length(), stringBuilder.Length(), SpanTypes.ExclusiveExclusive); } vh.Tags.SetText(stringBuilder, TextView.BufferType.Spannable); vh.Comments.Text = _Posts[position].Comments.ToString(); ImageAdapter adapter = new ImageAdapter(context, _Posts[position].Images); vh.Rotator.Adapter = adapter; } catch (Exception ex) { Insights.Initialize("0637c26a1b2e27693e05298f7c3c3a04c102a3c7", Application.Context); Insights.Report(ex, new Dictionary<string, string> { { "Message", ex.Message } }, Insights.Severity.Error); var text = ex.Message; } }
private static void RecursivePrepareSpannableIndexes( Context context, string fullText, SpannableStringBuilder text, List<IconFontDescriptorWrapper> iconFontDescriptors, int start) { string stringText = text.ToString(); // Try to find a {...} in the string and extract expression from it int startIndex = stringText.IndexOf("{", start, StringComparison.Ordinal); if (startIndex == -1) return; int endIndex = stringText.IndexOf("}", startIndex, StringComparison.Ordinal) + 1; string expression = stringText.Substring(startIndex + 1, endIndex - startIndex - 2); // Split the expression and retrieve the icon key string[] strokes = expression.Split(' '); string key = strokes[0]; // Loop through the descriptors to find a key match IconFontDescriptorWrapper iconFontDescriptor = null; IIcon icon = null; for (int i = 0; i < iconFontDescriptors.Count; i++) { iconFontDescriptor = iconFontDescriptors[i]; icon = iconFontDescriptor.GetIcon(key); if (icon != null) break; } // If no match, ignore and continue if (icon == null) { RecursivePrepareSpannableIndexes(context, fullText, text, iconFontDescriptors, endIndex); return; } // See if any more stroke within {} should be applied float iconSizePx = -1; int iconColor = int.MaxValue; float iconSizeRatio = -1; bool spin = false; bool baselineAligned = false; for (int i = 1; i < strokes.Length; i++) { string stroke = strokes[i]; // Look for "spin" if (stroke.Equals("spin", StringComparison.OrdinalIgnoreCase)) { spin = true; } // Look for "baseline" else if (stroke.Equals("baseline", StringComparison.OrdinalIgnoreCase)) { baselineAligned = true; } // Look for an icon size else if (Regex.IsMatch(stroke, "([0-9]*(\\.[0-9]*)?)dp")) { iconSizePx = DpToPx(context, float.Parse(stroke.Substring(0, stroke.Length - 2))); } else if (Regex.IsMatch(stroke, "([0-9]*(\\.[0-9]*)?)sp")) { iconSizePx = SpToPx(context, float.Parse(stroke.Substring(0, stroke.Length - 2))); } else if (Regex.IsMatch(stroke, "([0-9]*)px")) { iconSizePx = int.Parse(stroke.Substring(0, stroke.Length - 2)); } else if (Regex.IsMatch(stroke, "@dimen/(.*)")) { iconSizePx = GetPxFromDimen(context, context.PackageName, stroke.Substring(7)); if (iconSizePx < 0) throw new IllegalArgumentException("Unknown resource " + stroke + " in \"" + fullText + "\""); } else if (Regex.IsMatch(stroke, "@android:dimen/(.*)")) { iconSizePx = GetPxFromDimen(context, ANDROID_PACKAGE_NAME, stroke.Substring(15)); if (iconSizePx < 0) throw new IllegalArgumentException("Unknown resource " + stroke + " in \"" + fullText + "\""); } else if (Regex.IsMatch(stroke, "([0-9]*(\\.[0-9]*)?)%")) { iconSizeRatio = float.Parse(stroke.Substring(0, stroke.Length - 1)) / 100f; } // Look for an icon color else if (Regex.IsMatch(stroke, "#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})")) { iconColor = Color.ParseColor(stroke); } else if (Regex.IsMatch(stroke, "@color/(.*)")) { iconColor = GetColorFromResource(context, context.PackageName, stroke.Substring(7)); if (iconColor == int.MaxValue) throw new IllegalArgumentException("Unknown resource " + stroke + " in \"" + fullText + "\""); } else if (Regex.IsMatch(stroke, "@android:color/(.*)")) { iconColor = GetColorFromResource(context, ANDROID_PACKAGE_NAME, stroke.Substring(15)); if (iconColor == int.MaxValue) throw new IllegalArgumentException("Unknown resource " + stroke + " in \"" + fullText + "\""); } else { throw new IllegalArgumentException("Unknown expression " + stroke + " in \"" + fullText + "\""); } } // Replace the character and apply the typeface text = (SpannableStringBuilder)text.Replace(startIndex, endIndex, "" + icon.Character); text.SetSpan(new CustomTypefaceSpan(icon, iconFontDescriptor.GetTypeface(context), iconSizePx, iconSizeRatio, iconColor, spin, baselineAligned), startIndex, startIndex + 1, SpanTypes.InclusiveExclusive); RecursivePrepareSpannableIndexes(context, fullText, text, iconFontDescriptors, startIndex); }
private void setTextWithSyntaxHighlighting(TextView view, string input) { // don't display a trailing semicolon if there is one if (input.EndsWith(";")) { input = input.Substring(0, input.Length - 1); } var builder = new SpannableStringBuilder(input); var highlightColor = _context.Resources.GetColor(Resource.Color.SyntaxHighlight); var keywordMatches = Regex.Matches(input, _keywordRegex); foreach (Match match in keywordMatches) { var highlightColorSpan = new ForegroundColorSpan(highlightColor); builder.SetSpan(highlightColorSpan, match.Index, match.Index + match.Length, SpanTypes.InclusiveInclusive); } view.TextFormatted = builder; }
/** * Given a snippet string with matching segments surrounded by curly * braces, turn those areas into bold spans, removing the curly braces. */ public static ISpannable BuildStyledSnippet (Java.Lang.String snippet) { 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, SpanTypes.ExclusiveExclusive); delta += 2; } return builder; }