public override View GetChildView(int groupPosition, int childPosition, bool isLastChild, View convertView, ViewGroup parent) { var item = _dictGroup[_lstGroupId[groupPosition]][childPosition]; if (convertView == null) { convertView = _activity.LayoutInflater.Inflate(Android.Resource.Layout.SimpleListItem1, null); } var tv = convertView.FindViewById <TextView>(Android.Resource.Id.Text1); var text = item.FullName; var spannable = new SpannableString(text); spannable.SetSpan(new LeadingMarginSpanStandard(0, 15), 0, text.Length, 0); if (item.CompletionDate.HasValue && !item.CompletionDate.Value.Equals(DateTime.MinValue)) { // Strike out the text spannable.SetSpan(new StrikethroughSpan(), 0, text.Length, SpanTypes.InclusiveExclusive); } tv.TextFormatted = spannable; return(convertView); }
private void UpdateFormattedText() { if (Element?.FormattedText == null) { return; } var extensionType = typeof(FormattedStringExtensions); var type = extensionType.GetNestedType("FontSpan", BindingFlags.NonPublic); var ss = new SpannableString(Control.TextFormatted); var spans = ss.GetSpans(0, ss.ToString().Length, Class.FromType(type)); foreach (var span in spans) { var font = (Font)type.GetProperty("Font").GetValue(span, null); if ((font.FontFamily ?? Element.FontFamily) != null) { var start = ss.GetSpanStart(span); var end = ss.GetSpanEnd(span); var flags = ss.GetSpanFlags(span); ss.RemoveSpan(span); var newSpan = new CustomTypefaceSpan(Control, Element, font); ss.SetSpan(newSpan, start, end, flags); } } Control.TextFormatted = ss; }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); this.RequestWindowFeature(WindowFeatures.NoTitle); SetContentView(Resource.Layout.MyScores); txtBestScore = (TextView)FindViewById <TextView>(Resource.Id.txtBestScore); txtMediumScore = FindViewById <TextView>(Resource.Id.txtMediumScore); txtMemoryDescription = FindViewById <TextView>(Resource.Id.txtMemoryDescription); //String bestScoreText = "<![CDATA[<p><font color='#CBCBCB'>BEST SCORE</font> <font color='#FFFFFF'>3211</font></p> ]]>"; //txtBestScore.SetText((Html.FromHtml((bestScoreText)))); var bestScoreString = "BEST SCORE " + 0; var spanBestScore = new SpannableString(bestScoreString); spanBestScore.SetSpan(new ForegroundColorSpan(Color.Rgb(203, 203, 203)), 0, 10, 0); spanBestScore.SetSpan(new ForegroundColorSpan(Color.Rgb(255, 255, 255)), 11, bestScoreString.Length, 0); spanBestScore.SetSpan(new StyleSpan(TypefaceStyle.Normal), 0, 10, 0); spanBestScore.SetSpan(new StyleSpan(TypefaceStyle.Bold), 11, bestScoreString.Length, 0); txtBestScore.SetText(spanBestScore, TextView.BufferType.Spannable); var mediumScoreString = "MEDIUM SCORE " + 0; var spanMediumScore = new SpannableString(mediumScoreString); spanMediumScore.SetSpan(new ForegroundColorSpan(Color.Rgb(203, 203, 203)), 0, 12, 0); spanMediumScore.SetSpan(new ForegroundColorSpan(Color.Rgb(255, 255, 255)), 13, mediumScoreString.Length, 0); spanMediumScore.SetSpan(new StyleSpan(TypefaceStyle.Normal), 0, 12, 0); spanMediumScore.SetSpan(new StyleSpan(TypefaceStyle.Bold), 13, mediumScoreString.Length, 0); txtMediumScore.SetText(spanMediumScore, TextView.BufferType.Spannable); txtMemoryDescription.Text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sit amet purus pellentesque, vulputate tellus vitae, posuere nisl. Vivamus volutpat facilisis feugiat. Aliquam id dignissim purus. Cras ut iaculis tortor, ac dignissim diam. Aliquam varius, eros mattis placerat consequat, elit ligula lacinia mi, quis tincidunt orci enim quis risus. Cras pharetra diam felis, nec semper ipsum placerat nec. Phasellus feugiat at neque ac aliquet. Sed hendrerit, tellus a ultricies iaculis, orci odio ornare arcu, molestie lacinia risus orci non magna. Mauris auctor ut ante eu porttitor. Ut nunc elit, vehicula a tempus quis, commodo vel quam. Sed scelerisque, dolor ut tempus auctor, lorem massa suscipit dolor, accumsan tincidunt lectus metus nec massa."; }
public override Java.Lang.ICharSequence FilterFormatted(Java.Lang.ICharSequence source, int start, int end, ISpanned dest, int dstart, int dend) { for (var x = start; x < end; x++) { if (char.IsUpper(source.ElementAt(x))) { var v = new char[end - start]; TextUtils.GetChars(source.ToString(), start, end, v, 0); var s = new string(v).ToLower(CultureInfo.InvariantCulture); if (source is ISpanned sourceSpanned) { var sp = new SpannableString(s); TextUtils.CopySpansFrom(sourceSpanned, start, end, null, sp, 0); return(sp); } else { return(new Java.Lang.String(s)); } } } return(null); }
protected override void OnElementChanged(ElementChangedEventArgs <Xamarin.Forms.Button> e) { base.OnElementChanged(e); if (e.NewElement != null && this.Control != null) { if (iconSpan == null) { nativeBtn = (Android.Widget.Button) this.Control; iconButton = (IconButton)e.NewElement; iconFont = TrySetFont("fontawesome-webfont.ttf"); textFont = iconButton.Font.ToTypeface(); iconButton.IconSize = iconButton.IconSize == 0 ? (float)iconButton.FontSize : iconButton.IconSize; var computedString = BuildRawTextString(); iconSpan = BuildSpannableString(computedString); if (iconButton.TextAlignement == Xamarin.Forms.TextAlignment.Center) { nativeBtn.Gravity = Android.Views.GravityFlags.Center; } else if (iconButton.TextAlignement == Xamarin.Forms.TextAlignment.End) { nativeBtn.Gravity = Android.Views.GravityFlags.Right; } else if (iconButton.TextAlignement == Xamarin.Forms.TextAlignment.Start) { nativeBtn.Gravity = Android.Views.GravityFlags.Left; } nativeBtn.TransformationMethod = null; nativeBtn.SetPadding(0, 0, 0, 0); nativeBtn.AfterTextChanged += nativeBtn_AfterTextChanged; } } }
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); }
void ApplyKerning(float mKerningFactor) { if (Control.Text == null) { return; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < Control.Text.Length; i++) { builder.Append(Control.Text[i]); if (i + 1 < Control.Text.Length) { builder.Append("\u00A0"); } } SpannableString finalText = new SpannableString(builder.ToString()); if (builder.ToString().Length > 1) { for (int i = 1; i < builder.ToString().Length; i += 2) { finalText.SetSpan(new ScaleXSpan((mKerningFactor) / 6), i, i + 1, SpanTypes.ExclusiveExclusive); } } Control.SetText(finalText, BufferType.Spannable); }
protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); var toggle_alarm_operation = new Intent (this, typeof(FindPhoneService)); toggle_alarm_operation.SetAction(FindPhoneService.ACTION_TOGGLE_ALARM); var toggle_alarm_intent = PendingIntent.GetService (this, 0, toggle_alarm_operation, PendingIntentFlags.CancelCurrent); Android.App.Notification.Action alarm_action = new Android.App.Notification.Action (Resource.Drawable.alarm_action_icon, "", toggle_alarm_intent); var cancel_alarm_operation = new Intent (this, typeof(FindPhoneService)); cancel_alarm_operation.SetAction (FindPhoneService.ACTION_CANCEL_ALARM); var cancel_alarm_intent = PendingIntent.GetService (this, 0, cancel_alarm_operation, PendingIntentFlags.CancelCurrent); var title = new SpannableString ("Find My Phone"); title.SetSpan (new RelativeSizeSpan (0.85f), 0, title.Length(), SpanTypes.PointMark); notification = new Notification.Builder (this) .SetContentTitle (title) .SetContentText ("Tap to sound an alarm on phone") .SetSmallIcon (Resource.Drawable.ic_launcher) .SetVibrate (new long[]{ 0, 50 }) .SetDeleteIntent (cancel_alarm_intent) .Extend (new Notification.WearableExtender () .AddAction (alarm_action) .SetContentAction (0) .SetHintHideIcon (true)) .SetLocalOnly (true) .SetPriority ((int)NotificationPriority.Max); ((NotificationManager)GetSystemService (NotificationService)) .Notify (FIND_PHONE_NOTIFICATION_ID, notification.Build ()); Finish (); }
protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); // AZURE Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init(); // MAPs Xamarin.FormsMaps.Init(this, bundle); SQLitePCL.Batteries.Init(); global::Xamarin.Forms.Forms.Init(this, bundle); //LOGIN ((DroidPlatformProvider)DependencyService.Get <IPlatformProvider>()).Init(this); // QR CODE ZXing.Net.Mobile.Forms.Android.Platform.Init(); string param = this.Intent.GetStringExtra("param"); LoadApplication(new App(loadParameter: param)); var spannableString = new SpannableString(SupportActionBar.Title); spannableString.SetSpan(new TypefaceSpan("Avenir"), 0, spannableString.Length(), SpanTypes.ExclusiveExclusive); SupportActionBar.TitleFormatted = spannableString; }
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); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); //Set the view of the main layout SetContentView(Resource.Layout.activity_intro); // Setup toolbar SupportWidget.Toolbar toolbar = FindViewById <SupportWidget.Toolbar>(Resource.Id.toolbar); toolbar.Title = ""; SetSupportActionBar(toolbar); //create the ChestXRay AI model clickable TextView aboutTextView = FindViewById <TextView>(Resource.Id.txt_research_project); string modelName = GetString(Resource.String.intro_model_name); string researchProject = GetString(Resource.String.intro_research_project, modelName); SpannableString stringResearchProject = new SpannableString(researchProject); URLSpan clickableSpanChestXray = new URLSpan(SharedConstants.MLModelRepository); // Make modelName clickable int modelNameIndex = researchProject.IndexOf(modelName, StringComparison.CurrentCulture); stringResearchProject.SetSpan(clickableSpanChestXray, modelNameIndex, modelNameIndex + modelName.Length, SpanTypes.ExclusiveExclusive); aboutTextView.TextFormatted = stringResearchProject; aboutTextView.MovementMethod = new LinkMovementMethod(); FindViewById(Resource.Id.button_get_started).Click += delegate { ((MainApplication)this.Application).AppPrefManager.PassedIntroPage(); StartActivity(new Intent(this, typeof(ImageInput.ImageInputActivity))); Finish(); }; }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); var st = new SpannableString("Test"); st.SetSpan(new TypefaceSpan("Arial"), 0, st.Length(), SpanTypes.ExclusiveExclusive); ActionBar.TitleFormatted = st; }
private SpannableString GetCardTitle(string type, string remoteDeviceName) { SpannableString str = new SpannableString($"{type} from {remoteDeviceName}"); str.SetSpan(new StyleSpan(TypefaceStyle.Bold), 0, type.Length, SpanTypes.ExclusiveExclusive); return(str); }
/// <summary> /// Build the spannable according to the computed text, meaning set the right font, color and size to the text and icon char index /// </summary> /// <param name="computedString"></param> private SpannableString BuildSpannableString(string computedString) { SpannableString span = new SpannableString(computedString); if (!string.IsNullOrEmpty(_iconLabel.Icon)) { //set icon span.SetSpan(new CustomTypefaceSpan("fontawesome", _iconFont, _helper.GetSpanColor(_iconLabel.IconColor, Control.TextColors)), computedString.IndexOf(_iconLabel.Icon), computedString.IndexOf(_iconLabel.Icon) + _iconLabel.Icon.Length, SpanTypes.ExclusiveExclusive); //set icon size span.SetSpan(new AbsoluteSizeSpan((int)_iconLabel.IconSize, true), computedString.IndexOf(_iconLabel.Icon), computedString.IndexOf(_iconLabel.Icon) + _iconLabel.Icon.Length, SpanTypes.ExclusiveExclusive); } if (!string.IsNullOrEmpty(_iconLabel.Text)) { span.SetSpan(new CustomTypefaceSpan("", _textFont, _helper.GetSpanColor(_iconLabel.TextColor, Control.TextColors)), _textStartIndex, _textStopIndex, SpanTypes.ExclusiveExclusive); span.SetSpan(new AbsoluteSizeSpan((int)_iconLabel.FontSize, true), _textStartIndex, _textStopIndex, SpanTypes.ExclusiveExclusive); } return(span); }
private void init(View view) { if (!isOnline()) { mErrorDialog.Show(); } else { SpannableString s = new SpannableString("Payment Options"); typeface = Typeface.CreateFromAsset(navigationActivity.Assets, "JosefinSans-SemiBold.ttf"); s.SetSpan(new TypefaceSpan("Amaranth-Regular.ttf"), 0, s.Length(), SpanTypes.ExclusiveExclusive); s.SetSpan(new ForegroundColorSpan(navigationActivity.Resources.GetColor(Resource.Color.title)), 0, s.Length(), SpanTypes.ExclusiveExclusive); navigationActivity.TitleFormatted = s; mContosoText = view.FindViewById <TextView>(Resource.Id.contosocabsmoney); mWalletAmount = view.FindViewById <TextView>(Resource.Id.price); mAddMoney = view.FindViewById <TextView>(Resource.Id.addmoney); mSelectMode = view.FindViewById <TextView>(Resource.Id.paymentopttext); mCash = view.FindViewById <TextView>(Resource.Id.textcash); mCard = view.FindViewById <TextView>(Resource.Id.textcard); mWallet = view.FindViewById <TextView>(Resource.Id.textwallet); mContosoText.SetTypeface(typeface, TypefaceStyle.Normal); mWallet.SetTypeface(typeface, TypefaceStyle.Normal); mWalletAmount.SetTypeface(typeface, TypefaceStyle.Normal); mAddMoney.SetTypeface(typeface, TypefaceStyle.Normal); mCard.SetTypeface(typeface, TypefaceStyle.Normal); mCash.SetTypeface(typeface, TypefaceStyle.Normal); mSelectMode.SetTypeface(typeface, TypefaceStyle.Normal); mAddMoney.SetOnClickListener(this); } }
protected override View OnCreateCustomView(Context context, Android.Support.V7.App.AlertDialog.Builder builder, Bundle savedInstanceState) { string versionName; var appInfo = context.ApplicationInfo; try { var pkgInfo = context.PackageManager.GetPackageInfo(context.PackageName, 0); versionName = pkgInfo.VersionName; } catch (PackageManager.NameNotFoundException e) { versionName = ""; } ICharSequence msg = new SpannableString(GetFormattedHtml(context, Resource.String.about_message, versionName)); DialogTitle = context.GetText(Resource.String.about_title); builder.SetIcon(appInfo.Icon); builder.SetMessage(msg); builder.SetCancelable(true); builder.SetPositiveButton(Android.Resource.String.Ok, new SimpleDialogInterfaceOnClickListener()); return(null); }
public static void SetClickableSpan(this SpannableString spannableString, string allText, string clickableText, Action <CoreClickableSpan, View> onClick, string argument, Color?textColor = null, bool hideUnderline = false) { CoreUtility.ExecuteMethod("SetClickableSpan", delegate() { if (!textColor.HasValue) { textColor = Color.Black; } int ix = allText.IndexOf(clickableText); CoreClickableSpan clickableSpan = new CoreClickableSpan(onClick, argument, clickableText); clickableSpan.HideUnderline = hideUnderline; while (ix >= 0) { spannableString.SetSpan(clickableSpan, ix, ix + clickableText.Length, SpanTypes.ExclusiveExclusive); spannableString.SetSpan(new StyleSpan(Android.Graphics.TypefaceStyle.Bold), ix, ix + clickableText.Length, SpanTypes.ExclusiveExclusive); spannableString.SetSpan(new ForegroundColorSpan(textColor.Value), ix, ix + clickableText.Length, SpanTypes.ExclusiveExclusive); int nextIndex = allText.Substring(ix + clickableText.Length).IndexOf(clickableText); if (nextIndex >= 0) { ix = nextIndex + (ix + clickableText.Length); } else { ix = -1; // break out } } }); }
private void setCurrentClientTheme() { try { Typeface tf = Typeface.CreateFromAsset(Assets, Joyces.Helpers.Settings.MainFont); EditText editTextEmail = FindViewById <EditText>(Resource.Id.txtForgotViewEmail); editTextEmail.SetTypeface(tf, Android.Graphics.TypefaceStyle.Normal); editTextEmail.Hint = Lang.EMAIL; Button btnRegister = FindViewById <Button>(Resource.Id.btnForgotViewSubmit); btnRegister.SetTypeface(tf, Android.Graphics.TypefaceStyle.Normal); btnRegister.Text = Lang.RESET_PASSWORD; try { //Typeface tf = Typeface.CreateFromAsset(Assets, Joyces.Helpers.Settings.MainFont); SpannableString st = new SpannableString(Lang.FORGOT_PASSWORD); // st.SetSpan(new TypefaceSpan(this, "Signika-Regular.otf"), 0, st.Length(), SpanTypes.ExclusiveExclusive); st.SetSpan(tf, 0, st.Length(), SpanTypes.ExclusiveExclusive); ActionBar.TitleFormatted = st; } catch (Exception ee) { } } catch (Exception ex) { } }
private void SetFont(ref SpannableString converted, IBaseFont font, FontIndexPair pair, FontTag fontTag) { //set the text color if (font.Color != System.Drawing.Color.Empty) { converted.SetSpan(new ForegroundColorSpan(font.Color.ToNativeColor()), pair.StartIndex, pair.EndIndex, SpanTypes.ExclusiveInclusive); } if (fontTag != null && fontTag.FontAction == FontTagAction.Link) { CreateLink(ref converted, font, pair); } //set allignment if (font is Font) { Font taggedExtendedFont = font as Font; if (taggedExtendedFont.Alignment != TextAlignment.None) { Layout.Alignment alignment = taggedExtendedFont.Alignment == TextAlignment.Center ? Layout.Alignment.AlignCenter : Layout.Alignment.AlignNormal; converted.SetSpan(new AlignmentSpanStandard(alignment), pair.StartIndex, pair.EndIndex, SpanTypes.ExclusiveInclusive); } } if (_extendedFont != null) { //calculate the relative size to the regular font converted.SetSpan(new RelativeSizeSpan((float)font.Size / (float)_extendedFont.Size), pair.StartIndex, pair.EndIndex, SpanTypes.ExclusiveInclusive); } //set the custom typeface converted.SetSpan(new CustomTypefaceSpan("sans-serif", DroidAssetPlugin.GetCachedFont(font, _context)), pair.StartIndex, pair.EndIndex, SpanTypes.ExclusiveInclusive); }
/// <summary> /// Build the spannable according to the computed text, meaning set the right font, color and size to the text and icon char index /// </summary> /// <param name="computedString"></param> /// <returns></returns> private SpannableString BuildSpannableString(string computedString) { SpannableString span = new SpannableString(computedString); //if there is an icon if (!string.IsNullOrEmpty(iconButton.Icon)) { //set icon span.SetSpan(new CustomTypefaceSpan("fontawesome", iconFont, GetSpanColor(iconButton.IconColor)), computedString.IndexOf(iconButton.Icon), computedString.IndexOf(iconButton.Icon) + iconButton.Icon.Length, SpanTypes.ExclusiveExclusive); //set icon size span.SetSpan(new AbsoluteSizeSpan((int)iconButton.IconSize, true), computedString.IndexOf(iconButton.Icon), computedString.IndexOf(iconButton.Icon) + iconButton.Icon.Length, SpanTypes.ExclusiveExclusive); } //if there is text if (!string.IsNullOrEmpty(iconButton.Text)) { span.SetSpan(new CustomTypefaceSpan("", textFont, GetSpanColor(iconButton.TextColor)), textStartIndex, textStopIndex, SpanTypes.ExclusiveExclusive); span.SetSpan(new AbsoluteSizeSpan((int)iconButton.FontSize, true), textStartIndex, textStopIndex, SpanTypes.ExclusiveExclusive); } return(span); }
/// <summary> /// /// </summary> private void InitializeActivateSinceTextView() { if (MapViewModelBase.Mode == null) { return; } var NbrOfDaysFromNow = Math.Ceiling((DateTime.Now - MapViewModelBase.Mode.DateModeCreation).TotalDays); var textActivateSince = string.Empty; if (NbrOfDaysFromNow < 2) { textActivateSince = string.Format(Resources.GetString(Resource.String.metaData_activateSinceSingle), NbrOfDaysFromNow); } else { textActivateSince = string.Format(Resources.GetString(Resource.String.metaData_activateSince), NbrOfDaysFromNow); } var resultTuple = SeekiosApp.Helper.StringHelper.GetStartAndEndIndexOfNumberInString(textActivateSince); var formattedTextActivateSince = new SpannableString(textActivateSince); formattedTextActivateSince.SetSpan(new ForegroundColorSpan(Color.ParseColor(App.MainColor)), resultTuple.Item1, resultTuple.Item2, 0); ActivateSinceTextView.SetText(formattedTextActivateSince, TextView.BufferType.Spannable); }
public static SpannableString FormatText(List <ParsedMessage> messagesToDisplay) { StringBuilder stringBuilder = new StringBuilder(); List <MessageInfo> messageInfos = new List <MessageInfo>(); foreach (ParsedMessage parsedMessage in messagesToDisplay) { MessageInfo messageInfo = new MessageInfo(); messageInfo.Start = stringBuilder.Length; messageInfo.End = messageInfo.Start + parsedMessage.Message.Length; messageInfo.Color = SetColor(parsedMessage); messageInfos.Add(messageInfo); stringBuilder.Append(parsedMessage.Message); } SpannableString spannableString = new SpannableString(stringBuilder.ToString()); foreach (MessageInfo messageInfo in messageInfos) { spannableString.SetSpan(new ForegroundColorSpan(messageInfo.Color), messageInfo.Start, messageInfo.End, 0); } return(spannableString); }
public static void SetStyleSpan(this SpannableString spannableString, string allText, string styleText, TypefaceStyle style, Color textColor, Typeface typeFace = null, float typeFaceSize = 0) { CoreUtility.ExecuteMethod("SetStyleSpan", delegate() { int ix = allText.IndexOf(styleText); while (ix >= 0) { spannableString.SetSpan(new StyleSpan(style), ix, ix + styleText.Length, SpanTypes.ExclusiveExclusive); if (textColor != Color.Transparent) { spannableString.SetSpan(new ForegroundColorSpan(textColor), ix, ix + styleText.Length, SpanTypes.ExclusiveExclusive); } if (typeFace != null) { spannableString.SetSpan(new CustomTypefaceSpan(typeFace, typeFaceSize), ix, ix + styleText.Length, SpanTypes.ExclusiveExclusive); } int nextIndex = allText.Substring(ix + styleText.Length).IndexOf(styleText); if (nextIndex >= 0) { ix = nextIndex + (ix + styleText.Length); } else { ix = -1; // break out } } }); }
public static SpannableString SpanText(string text, Object span) { SpannableString spannableString = new SpannableString(text); spannableString.SetSpan(span, 0, text.Length, SpanTypes.ExclusiveExclusive); return(spannableString); }
private void UpdateNativeControl() { try { if ((Element as ItemLabel).IsLucky) { ImageSpan span = new ImageSpan(this.Context, Resource.Drawable.luckyStar); SpannableString spanStr = new SpannableString(Element.Text); spanStr.SetSpan(span, spanStr.Length() - 1, spanStr.Length(), SpanTypes.InclusiveExclusive); this.Control.SetText(spanStr, Android.Widget.TextView.BufferType.Normal); } else { if (Build.VERSION.SdkInt >= BuildVersionCodes.N) { this.Control.SetText(Html.FromHtml(Element.Text, FromHtmlOptions.ModeLegacy), Android.Widget.TextView.BufferType.Normal); } else { this.Control.SetText(Html.FromHtml(Element.Text), Android.Widget.TextView.BufferType.Normal); } } } catch (System.Exception ex) { this.Control.Text = Element.Text; Crashes.TrackError(ex); } }
public Java.Lang.ICharSequence FilterFormatted(Java.Lang.ICharSequence source, int start, int end, global::Android.Text.ISpanned dest, int dstart, int dend) { var s = source.ToString(); var d = dest.ToString(); var proposal = d.Remove(dstart, dend - dstart).Insert(dstart, s.Substring(start, end - start)); if (_onChangeDelegate(proposal)) return null; else { var r = new Java.Lang.String(d.Substring(dstart, dend - dstart)); if (source is ISpanned) { // This spannable thing here, is needed to copy information about which part of // the string is being under composition by the keyboard (or other spans). A // spannable string has support for extra information to the string, besides // its characters and that information must not be lost! var ssb = new SpannableString(r); var spannableEnd = (end <= ssb.Length()) ? end : ssb.Length(); global::Android.Text.TextUtils.CopySpansFrom((ISpanned)source, start, spannableEnd, null, ssb, 0); return ssb; } else return r; } }
public virtual void AddText(string text, string colorStr, double alpha = 1.0) { var color = UtilsDroid.String2Color(colorStr); SpannableString newText = new SpannableString(text); newText.SetSpan(new ForegroundColorSpan(color), 0, text.Length, SpanTypes.InclusiveExclusive); if (m_viewX is EditText) { var editTextView = m_viewX as EditText; if (editTextView.Text.Length > 0) { editTextView.Append("\n"); } editTextView.Append(newText); } else if (m_viewX is TextView) { var textView = m_viewX as TextView; if (textView.Text.Length > 0) { textView.Append("\n"); } textView.Append(newText); } }
/// <summary> /// Returns a SpannableString containing interactive sources for subtitles. /// </summary> /// <param name="action">Action that should be started when the user interacts with the source.</param> /// <param name="textWithSubstitutes">The parsed text with substitutes</param> /// <param name="sources">The parsed sources</param> /// <returns>A SpannableString parsed from the textWithSubstitutes for the subtitles. Returns null, if the provided action is null.</returns> public SpannableString CreateSubtitlesText(IInteractiveSourceAction action, string textWithSubstitutes, List <Source> sources) { if (action == null) { return(null); } var str = new SpannableString(textWithSubstitutes); foreach (var src in sources) { if (src == null) { continue; } str.SetSpan( ConvertSrcToClickableSpan(src, action), src.StartIndex, src.StartIndex + src.SubstituteText.Length, SpanTypes.ExclusiveExclusive); } return(str); }
void UpdateText() { if (Element.FormattedText != null) { FormattedString formattedText = Element.FormattedText ?? Element.Text; #pragma warning disable 618 // We will need to update this when .Font goes away _view.TextFormatted = _spannableString = formattedText.ToAttributed(Element.Font, Element.TextColor, _view); #pragma warning restore 618 _wasFormatted = true; } else { if (_wasFormatted) { _view.SetTextColor(_labelTextColorDefault); _lastUpdateColor = Color.Default; } _view.Text = Element.Text; UpdateColor(); UpdateFont(); _wasFormatted = false; } _lastSizeRequest = null; }
public void ShowPlaceInfo(Context context, string[] info) { txtAddressFoodiPlaces.Visibility = ViewStates.Visible; txtNameFoodiPlaces.Visibility = ViewStates.Visible; frReviews.Visibility = ViewStates.Visible; lnReviewsTop.Visibility = ViewStates.Visible; txtTopReviewsDetail.Visibility = ViewStates.Visible; lnMoreReviews.Visibility = ViewStates.Gone; txtMore.Visibility = ViewStates.Visible; var score = (float)Math.Round(float.Parse(info[0], System.Globalization.CultureInfo.InvariantCulture) / 2, 2); ratingBar.Value = score; txtScore.Text = score.ToString("0.00"); txtNameFoodiPlaces.Text = info[1]; txtAddressFoodiPlaces.Text = "Địa chỉ: " + info[2] + "."; Random random = new Random(); int randomPosition = random.Next(1, reviews.Count - 1); Review review = reviews[randomPosition]; sfRatingTopReview.Value = review.Score; DisplayCustomRatingBar(sfRatingTopReview); txtTopReviewsDetail.Text = review.Detail; txtTopReviewsDate.Text = review.Date.ToShortDateString() + "\n" + review.Name; SpannableString ss = new SpannableString("Xem Thêm"); var clickableSpan = new MyClickableSpan(); clickableSpan.Click += v => LoadReviews(); ss.SetSpan(clickableSpan, 0, 8, SpanTypes.ExclusiveExclusive); txtMore.TextFormatted = ss; txtMore.MovementMethod = new LinkMovementMethod(); }
private void setOnClick(LinearLayout lay, int i) { lay.Click += (object sender, EventArgs e) => { if (selectedLayout != null) { TextView oldTextView1 = (TextView)selectedLayout.FindViewById(Resource.Id.text3); TextView oldTextView2 = (TextView)selectedLayout.FindViewById(Resource.Id.text4); ImageView newImageView = (ImageView)selectedLayout.FindViewById(Resource.Id.imageview1); oldTextView1.SetTextColor(Color.ParseColor("#ffffff")); oldTextView2.SetTextColor(Color.ParseColor("#ffffff")); newImageView.SetImageResource(selectedData.Type); } TextView newTextView1 = (TextView)lay.FindViewById(Resource.Id.text3); TextView newTextView12 = (TextView)lay.FindViewById(Resource.Id.text4); ImageView newimageView = (ImageView)lay.FindViewById(Resource.Id.imageview1); WeatherData data = dataSource[i]; newTextView1.SetTextColor(Color.ParseColor("#fbb03b")); newTextView12.SetTextColor(Color.ParseColor("#fbb03b")); newimageView.SetImageResource(data.SelectedType); ImageView imageView = (ImageView)linearLayout.FindViewById(Resource.Id.imageview); imageView.SetImageResource(data.Type); TextView degreeText = (TextView)linearLayout.FindViewById(Resource.Id.text); String s2 = "" + data.Temperature + (char)0x00B0 + "/12"; SpannableString ss2 = new SpannableString(s2); ss2.SetSpan(new RelativeSizeSpan(2f), 0, 4, SpanTypes.ExclusiveExclusive); degreeText.SetText(ss2, TextView.BufferType.Normal); TextView dayText = (TextView)linearLayout.FindViewById(Resource.Id.text1); dayText.Text = dataSource[i].Date; selectedData = data; selectedLayout = lay; }; }
public Java.Lang.ICharSequence ConvertTemperatureToAlertedStyle(Context context, double temperature, string format, params object[] args) { var temp = ConvertTemperature(temperature); var tempToString = Format(format, temp, args); var spannable = new SpannableString(tempToString); int styleId; if (IsColdTemperatureAlerted(temp)) { styleId = Resource.Style.coldAlertedTemperatureTextStyle; } else if (IsHotTemperatureAlerted(temp)) { styleId = Resource.Style.hotAlertedTemperatureTextStyle; } else { return(spannable); } spannable.SetSpan(new TextAppearanceSpan(context, styleId), 0, tempToString.Length, SpanTypes.ExclusiveExclusive); return(spannable); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.Conditions); Typeface tf = Typeface.CreateFromAsset(Assets, "FiraSansRegular.ttf"); var headerTv = FindViewById <TextView>(Resource.Id.headerTV); var conditionsTv = FindViewById <TextView>(Resource.Id.conditionsTV); headerTv.Text = TranslationHelper.GetString("conditionsHeader", _ci); headerTv.SetTypeface(tf, TypefaceStyle.Normal); conditionsTv.SetTypeface(tf, TypefaceStyle.Normal); SpannableString content = new SpannableString(Constants.licenseUrl); content.SetSpan(new UnderlineSpan(), 0, content.Length(), 0); conditionsTv.SetText(content, TextView.BufferType.Spannable); //conditionsTV.Text = "здесь будут условия соглашения здесь будут условия соглашения здесь будут условия соглашения здесь будут условия соглашения здесь будут условия соглашения здесь будут условия соглашения "; conditionsTv.Click += (s, e) => { var uri = Android.Net.Uri.Parse(Constants.licenseUrl); var intent = new Intent(Intent.ActionView, uri); StartActivity(intent); }; FindViewById <RelativeLayout>(Resource.Id.backRL).Click += (s, e) => OnBackPressed(); }
public override bool OnOptionsItemSelected(IMenuItem item) { switch (item.ItemId) { case Resource.Id.Clear: var progressDialog = ProgressDialog.Show(this, Resources.GetString( Resource.String.ClearSessionProgressTitle), Resources.GetString(Resource.String.ClearSessionProgressText), true); Runner.Instance.ClearSession(() => RunOnUiThread(() => { _results.Clear(); _adapter.NotifyDataSetChanged(); progressDialog.Dismiss(); })); return true; case Resource.Id.Namespaces: StartActivity(typeof(UpdateNamespacesActivity)); return true; case Resource.Id.Variables: showVariables(); return true; case Resource.Id.Settings: StartActivity(typeof(SettingsActivity)); return true; case Resource.Id.About: var packageInfo = PackageManager.GetPackageInfo(PackageName, 0); var aboutContent = new SpannableString(string.Format(Resources.GetString(Resource.String.AboutContent), packageInfo.VersionName)); Linkify.AddLinks(aboutContent, MatchOptions.All); var dialog = new AlertDialog.Builder(this) .SetTitle(Resource.String.AboutTitle) .SetMessage(aboutContent) .SetPositiveButton(Resource.String.AboutOkButton, delegate { }) .Show(); ((TextView)dialog.FindViewById(AndroidCore.Resource.Id.Message)).MovementMethod = LinkMovementMethod.Instance; return true; } return base.OnOptionsItemSelected(item); }
public static SpannableString ToAttributed(this FormattedString formattedString, Font defaultFont, Color defaultForegroundColor, TextView view) { if (formattedString == null) return null; var builder = new StringBuilder(); foreach (Span span in formattedString.Spans) { if (span.Text == null) continue; builder.Append(span.Text); } var spannable = new SpannableString(builder.ToString()); var c = 0; foreach (Span span in formattedString.Spans) { if (span.Text == null) continue; int start = c; int end = start + span.Text.Length; c = end; if (span.ForegroundColor != Color.Default) { spannable.SetSpan(new ForegroundColorSpan(span.ForegroundColor.ToAndroid()), start, end, SpanTypes.InclusiveExclusive); } else if (defaultForegroundColor != Color.Default) { spannable.SetSpan(new ForegroundColorSpan(defaultForegroundColor.ToAndroid()), start, end, SpanTypes.InclusiveExclusive); } if (span.BackgroundColor != Color.Default) { spannable.SetSpan(new BackgroundColorSpan(span.BackgroundColor.ToAndroid()), start, end, SpanTypes.InclusiveExclusive); } if (!span.IsDefault()) #pragma warning disable 618 // We will need to update this when .Font goes away spannable.SetSpan(new FontSpan(span.Font, view), start, end, SpanTypes.InclusiveInclusive); #pragma warning restore 618 else if (defaultFont != Font.Default) spannable.SetSpan(new FontSpan(defaultFont, view), start, end, SpanTypes.InclusiveInclusive); } return spannable; }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate (savedInstanceState); SetContentView (Resource.Layout.link); // text1 shows the android:autoLink property, which // automatically linkifies things like URLs and phone numbers // found in the text. No java code is needed to make this // work. // text2 has links specified by putting <a> tags in the string // resource. By default these links will appear but not // respond to user input. To make them active, you need to // call setMovementMethod() on the TextView object. TextView t2 = (TextView)FindViewById (Resource.Id.text2); t2.MovementMethod = LinkMovementMethod.Instance; // text3 shows creating text with links from HTML in the Java // code, rather than from a string resource. Note that for a // fixed string, using a (localizable) resource as shown above // is usually a better way to go; this example is intended to // illustrate how you might display text that came from a // dynamic source (eg, the network). //TextView t3 = (TextView)FindViewById (Resource.Id.text3); //t3.Text = Html.FromHtml( // "<b>text3:</b> Text with a " + // "<a href=\"http://www.google.com\">link</a> " + // "created in the Java source code using HTML."); //t3.MovementMethod = LinkMovementMethod.Instance; // text4 illustrates constructing a styled string containing a // link without using HTML at all. Again, for a fixed string // you should probably be using a string resource, not a // hardcoded value. SpannableString ss = new SpannableString ("text4: Click here to dial the phone."); ss.SetSpan (new StyleSpan (TypefaceStyle.Bold), 0, 6, SpanTypes.ExclusiveExclusive); ss.SetSpan (new URLSpan ("tel:4155551212"), 13, 17, SpanTypes.ExclusiveExclusive); TextView t4 = (TextView)FindViewById (Resource.Id.text4); t4.TextFormatted = ss; t4.MovementMethod = LinkMovementMethod.Instance; }
public static SpannableString ParseStringForKeywords(FragmentManager fragmentManager, int containerId, string str) { if (String.IsNullOrEmpty(str)) { return new SpannableString(""); } SpannableString spannableString = new SpannableString(str); List<Range> handles = RangedOfStringInString("@", str, str); if (handles.Count > 0) { for (int i = 0; i < handles.Count; i++) { ClickableSpan clickableSpan = new MyClickableSpan(str.Substring(handles[i].Start, handles[i].End), (string obj) => { if (obj.IndexOf('@') == 0) { TenServiceHelper.GoToGuestProfile(fragmentManager, containerId, obj); } }); spannableString.SetSpan(clickableSpan, handles[i].Start, handles[i].Start + handles[i].End, SpanTypes.ExclusiveExclusive); } } List<Range> hashes = RangedOfStringInString("#", str, str); if (hashes.Count > 0) { for (int i = 0; i < hashes.Count; i++) { ClickableSpan clickableSpan = new MyClickableSpan(str.Substring(hashes[i].Start, hashes[i].End), (string obj) => { if (obj.IndexOf('#') == 0) { TenServiceHelper.GoToSearchTags(fragmentManager, containerId, obj); } }); spannableString.SetSpan(clickableSpan, hashes[i].Start, hashes[i].Start + hashes[i].End, SpanTypes.ExclusiveExclusive); } } return spannableString; }
public static SpannableString GetLettersMarked(List<string> markedLetters, bool capitalize) { var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; if (capitalize == false) alphabet = alphabet.ToLower(); if (markedLetters == null) return new SpannableString(alphabet); var spannable = new SpannableString(alphabet); foreach (var letter in markedLetters) { var index = Letters.IndexOf(letter.ToUpper()); spannable.SetSpan(new ForegroundColorSpan(Android.Graphics.Color.Red), index, index + 1, SpanTypes.ExclusiveExclusive); } return spannable; }
/// <summary> /// Posts a local notification for the given geofence ID, with an option to check in /// </summary> /// <param name="geofenceId">The geodence id that the user has triggered</param> /// <param name="dataItemUri">The Uri for the DataItem that triggered this notification. Used to delete this DataItem /// when the notification is dismissed</param> void PostNotificationForGeofenceId(String geofenceId, Android.Net.Uri dataItemUri) { // Use the geofenceId to determine the title and background of the check-in notification. // A SpannableString is used for the notification title for resizing capabilities SpannableString checkInTitle; Bitmap notificationBackground; if (Constants.ANDROID_BUILDING_ID.Equals (geofenceId)) { checkInTitle = new SpannableString (GetText (Resource.String.android_building_title)); notificationBackground = BitmapFactory.DecodeResource (Resources, Resource.Drawable.android_building); } else if (Constants.YERBA_BUENA_ID.Equals (geofenceId)) { checkInTitle = new SpannableString (GetText (Resource.String.yerba_buena_title)); notificationBackground = BitmapFactory.DecodeResource (Resources, Resource.Drawable.yerba_buena); } else { Log.Error (Constants.TAG, "Unrecognized geofence id: " + geofenceId); return; } // Resize the title to avoid truncation checkInTitle.SetSpan (new RelativeSizeSpan (0.8f), 0, checkInTitle.Length(), SpanTypes.PointMark); Intent checkInOperation = new Intent (this, typeof(CheckInAndDeleteDataItemsService)).SetData (dataItemUri); PendingIntent checkInIntent = PendingIntent.GetService (this, 0, checkInOperation.SetAction (Constants.ACTION_CHECK_IN), PendingIntentFlags.CancelCurrent); PendingIntent deleteDataItemIntent = PendingIntent.GetService (this, 0, checkInOperation.SetAction (Constants.ACTION_DELETE_DATA_ITEM), PendingIntentFlags.CancelCurrent); // This action will be embedded into the notification var checkInAction = new Notification.Action (Resource.Drawable.ic_action_check_in, GetText (Resource.String.check_in_prompt), checkInIntent); Notification notification = new Notification.Builder (this) .SetContentTitle (checkInTitle) .SetContentText (GetText (Resource.String.check_in_prompt)) .SetSmallIcon (Resource.Drawable.ic_launcher) .SetDeleteIntent (deleteDataItemIntent) .Extend (new Notification.WearableExtender () .SetBackground (notificationBackground) .AddAction (checkInAction) .SetContentAction (0) .SetHintHideIcon (true)) .SetLocalOnly (true) .Build (); GetSystemService (NotificationService).JavaCast<NotificationManager> ().Notify (Constants.NOTIFICATION_ID, notification); }
/// <summary> /// Rebuild the all span in and set it into the label /// </summary> private void SetText() { var computedString = BuildRawTextString(); iconSpan = BuildSpannableString(computedString); if (iconLabel.TextAlignement == Xamarin.Forms.TextAlignment.Center) { nativeLabel.Gravity = Android.Views.GravityFlags.Center; } else if (iconLabel.TextAlignement == Xamarin.Forms.TextAlignment.End) { nativeLabel.Gravity = Android.Views.GravityFlags.Right; } else if (iconLabel.TextAlignement == Xamarin.Forms.TextAlignment.Start) { nativeLabel.Gravity = Android.Views.GravityFlags.Left; } nativeLabel.SetText(iconSpan, TextView.BufferType.Spannable); }
/// <summary> /// Handles the Element Changed event messages /// </summary> /// <param name="e">The e.</param> protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e) { base.OnElementChanged(e); if (e.NewElement != null && this.Control != null) { if (_helper == null) _helper = new TextViewRenderHelper(Context); if (_iconSpan == null) { _nativeBtn = (Android.Widget.Button)this.Control; _iconButton = (IconButton)e.NewElement; _iconFont = _helper.TrySetFont("fontawesome-webfont.ttf"); _textFont = _iconButton.Font.ToTypeface(); _iconButton.IconSize = _iconButton.IconSize == 0 ? (float)_iconButton.FontSize : _iconButton.IconSize; var computedString = BuildRawTextString(); _iconSpan = BuildSpannableString(computedString); if (_iconButton.TextAlignement == Xamarin.Forms.TextAlignment.Center) { _nativeBtn.Gravity = Android.Views.GravityFlags.Center; } else if (_iconButton.TextAlignement == Xamarin.Forms.TextAlignment.End) { _nativeBtn.Gravity = Android.Views.GravityFlags.Right; } else if (_iconButton.TextAlignement == Xamarin.Forms.TextAlignment.Start) { _nativeBtn.Gravity = Android.Views.GravityFlags.Left; } _nativeBtn.TransformationMethod = null; _nativeBtn.SetPadding(0, 0, 0, 0); _nativeBtn.AfterTextChanged += nativeBtn_AfterTextChanged; } } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); this.SetContentView(Resource.Layout.activity_playground); //Show how to style the text of an existing TextView TextView tv1 = this.FindViewById<TextView>(Resource.Id.test1); new Iconics.IconicsBuilder().Ctx(this) .Style(new ForegroundColorSpan(Color.White), new BackgroundColorSpan(Color.Black), new RelativeSizeSpan(2f)) .StyleFor("faw-adjust", new BackgroundColorSpan(Color.Red), new ForegroundColorSpan(Color.ParseColor("#33000000")), new RelativeSizeSpan(2f)) .On(tv1) .Build(); //You can also do some advanced stuff like setting an image within a text TextView tv2 = this.FindViewById<TextView>(Resource.Id.test5); SpannableString sb = new SpannableString(tv2.Text); IconicsDrawable d = new IconicsDrawable(this, FontAwesome.Icon.FawAndroid).SizeDp(48).PaddingDp(4); sb.SetSpan(new ImageSpan(d, SpanAlign.Bottom), 1, 2, SpanTypes.ExclusiveExclusive); tv2.Text = sb.ToString(); //Set the icon of an ImageView (or something else) as drawable ImageView iv2 = this.FindViewById<ImageView>(Resource.Id.test2); iv2.SetImageDrawable(new IconicsDrawable(this, FontAwesome.Icon.FawThumbsOUp).SizeDp(48).Color(Color.ParseColor("#aaFF0000")).ContourWidthDp(1)); //Set the icon of an ImageView (or something else) as bitmap ImageView iv3 = this.FindViewById<ImageView>(Resource.Id.test3); iv3.SetImageBitmap(new IconicsDrawable(this, new FontAwesome(), FontAwesome.Icon.FawAndroid).Color(Color.ParseColor("#deFF0000")).ToBitmap()); //Show how to style the text of an existing button (NOT WORKING AT THE MOMENT) Button b4 = this.FindViewById<Button>(Resource.Id.test4); new Iconics.IconicsBuilder().Ctx(this) .Style(new BackgroundColorSpan(Color.Black)) .Style(new RelativeSizeSpan(2f)) .Style(new ForegroundColorSpan(Color.White)) .On(b4) .Build(); }
//displays totem info private void SetInfo() { body.Text = _appController.CurrentTotem.body; if (hidden) { title_synonyms.Text = "..."; body.Text = _appController.CurrentTotem.body.Replace(_appController.CurrentTotem.title, "..."); } else { number.Text = _appController.CurrentTotem.number + ". "; Typeface Verveine = Typeface.CreateFromAsset(Assets, "fonts/Verveine W01 Regular.ttf"); //code to get formatting right //title and synonyms are in the same TextView //font, size,... are given using spans if (_appController.CurrentTotem.synonyms != null) { string titlestring = _appController.CurrentTotem.title; string synonymsstring = " - " + _appController.CurrentTotem.synonyms + " "; Typeface Din = Typeface.CreateFromAsset(Assets, "fonts/DINPro-Light.ttf"); ISpannable sp = new SpannableString(titlestring + synonymsstring); sp.SetSpan(new CustomTypefaceSpan("sans-serif", Verveine, 0), 0, titlestring.Length, SpanTypes.ExclusiveExclusive); sp.SetSpan(new CustomTypefaceSpan("sans-serif", Din, TypefaceStyle.Italic, ConvertDPToPixels(17)), titlestring.Length, titlestring.Length + synonymsstring.Length, SpanTypes.ExclusiveExclusive); title_synonyms.TextFormatted = sp; } else { title_synonyms.Text = _appController.CurrentTotem.title; title_synonyms.SetTypeface(Verveine, 0); } } }
public void SetDetails(string details) { if (details != null) { SpannableString ssbDetail = new SpannableString(details); ssbDetail.SetSpan(mDetailSpan, 0, ssbDetail.Length(), 0); mDetails = ssbDetail; } }
public void SetTitle(string title) { if (title != null) { SpannableString ssbTitle = new SpannableString(title); ssbTitle.SetSpan(mTitleSpan, 0, ssbTitle.Length(), 0); mTitle = ssbTitle; } }
private void PopulateView(View ev, string protocolId, int pos) { ImageView iv = (ImageView)ev.FindViewById(Resource.Id.filestorage_logo); Drawable drawable = App.Kp2a.GetResourceDrawable("ic_storage_" + protocolId); iv.SetImageDrawable(drawable); String title = App.Kp2a.GetResourceString("filestoragename_" + protocolId); var str = new SpannableString(title); _textView.TextFormatted = str; }
void UpdateUITime (DateTime? date = null) { var dt = date.HasValue ? date.Value : DateTime.UtcNow.ToLocalTime (); wheelSeconds.SetProgress (dt.Second); //var fmt = "h:mm tt"; var fmt = "h:mm"; if (WearListenerService.Settings.Use24Clock) fmt = "H:mm"; var str = dt.ToString (fmt).ToUpperInvariant (); var ss = new SpannableString (str); ss.SetSpan (new StyleSpan (Android.Graphics.TypefaceStyle.Bold), 0, str.IndexOf (':'), SpanTypes.ExclusiveExclusive); if (fmt.Contains (" ")) { var ttIndex = str.LastIndexOf (' ') + 1; ss.SetSpan (new ForegroundColorSpan (Android.Graphics.Color.Gray), ttIndex, ttIndex + 2, SpanTypes.ExclusiveExclusive); ss.SetSpan (new RelativeSizeSpan (0.8f), ttIndex, ttIndex + 2, SpanTypes.ExclusiveExclusive); } time.TextFormatted = ss; }
private void Rebind () { if (!enabled || DurationTextView == null) return; var durationShown = digitsEntered > 0 ? newDuration : oldDuration; var durationText = durationShown.ToString (); var durationSpannable = new SpannableString (durationText); durationSpannable.SetSpan ( new ForegroundColorSpan (Color.LightGray), 0, durationSpannable.Length (), SpanTypes.InclusiveExclusive); if (digitsEntered > 0) { // Divider var sepIdx = durationText.IndexOf (":", StringComparison.Ordinal); if (sepIdx >= 0) { durationSpannable.SetSpan ( new ForegroundColorSpan (Color.Black), sepIdx, sepIdx + 1, SpanTypes.InclusiveExclusive); } // Color entered minutes durationSpannable.SetSpan ( new ForegroundColorSpan (Color.Black), durationText.Length - (Math.Min (digitsEntered, 2)), durationText.Length, SpanTypes.InclusiveExclusive); // Color entered hours if (digitsEntered > 2) { durationSpannable.SetSpan ( new ForegroundColorSpan (Color.Black), 2 - (digitsEntered - 2), 2, SpanTypes.InclusiveExclusive); } } DurationTextView.SetText (durationSpannable, TextView.BufferType.Spannable); int num = 0; foreach (var numButton in numButtons) { numButton.Enabled = digitsEntered < 4; num += 1; } DeleteImageButton.Enabled = digitsEntered > 0; Add5Button.Enabled = newDuration.IsValid && newDuration.AddMinutes (5).IsValid; Add30Button.Enabled = newDuration.IsValid && newDuration.AddMinutes (30).IsValid; OkButton.Enabled = digitsEntered > 0 && newDuration.IsValid; }
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; } }
public ICharSequence TerminateTokenFormatted(ICharSequence text) { int i = text.Length(); while (i > 0 && text.CharAt(i - 1) == ' ') { i--; } if (i > 0 && SplitChar.Contains(text.CharAt(i - 1))) { return text; } else { // Try not to use a space as a token character var token = (SplitChar.Count > 1 && SplitChar[0] == ' ' ? SplitChar[1] : SplitChar[0]) + " "; if (text is ISpanned) { SpannableString sp = new SpannableString(text + token); TextUtils.CopySpansFrom((ISpanned)text, 0, text.Length(), null, sp, 0); return sp; } else { return (text + token).ToAndroidString(); } } }
private void Render(Marker marker, View view) { var resourceId = 0; if (parent._crueltyLookup.ContainsKey(marker.Id)) { CrueltySpot spot = parent._crueltyLookup[marker.Id]; if (spot.CrueltySpotCategory.IconName != null) { resourceId = parent.Resources.GetIdentifier(spot.CrueltySpotCategory.IconName.Replace(".png", ""), "drawable", parent.PackageName); } } ((ImageView)view.FindViewById(Resource.Id.badge)).SetImageResource(resourceId); String title = marker.Title; TextView titleUi = ((TextView)view.FindViewById(Resource.Id.title)); if (title != null) { // Spannable string allows us to edit the formatting of the text. SpannableString titleText = new SpannableString(title); // FIXME: this somehow rejects to compile //titleText.SetSpan (new ForegroundColorSpan(Color.Red), 0, titleText.Length, st); titleUi.TextFormatted = (titleText); } else { titleUi.Text = (""); } String snippet = marker.Snippet; TextView snippetUi = ((TextView)view.FindViewById(Resource.Id.snippet)); if (snippet != null) { SpannableString snippetText = new SpannableString(snippet); // snippetText.SetSpan(new ForegroundColorSpan(Color.Magenta), 0, 10, 0); // snippetText.SetSpan(new ForegroundColorSpan(Color.Blue), 12, 21, 0); snippetUi.TextFormatted = (snippetText); } else { snippetUi.Text = (""); } }
/// <summary> /// A method for getting tokens containing mutible words /// </summary> private ICharSequence InnerToken(ICharSequence text) { int i = text.Length(); // Find the first space in the Token, going backwards while (i > 0 && text.CharAt(i - 1) == ' ') { i--; } if (i > 0 && text.CharAt(i - 1) == ' ') { return text; } else { if (text.GetType().IsInstanceOfType(typeof(ISpanned))) { SpannableString sp = new SpannableString(text + " "); TextUtils.CopySpansFrom((ISpanned)text, 0, text.Length(), Java.Lang.Class.FromType(typeof(Java.Lang.Object)), sp, 0); return sp; } else { return new Java.Lang.String(text + " "); } } }
private void PopulateView(View ev, PwEntry pw, int pos) { _entry = pw; _pos = pos; ImageView iv = (ImageView)ev.FindViewById(Resource.Id.entry_icon); bool isExpired = pw.Expires && pw.ExpiryTime < DateTime.Now; if (isExpired) { App.Kp2a.GetDb().DrawableFactory.AssignDrawableTo(iv, Resources, App.Kp2a.GetDb().KpDatabase, PwIcon.Expired, PwUuid.Zero); } else { App.Kp2a.GetDb().DrawableFactory.AssignDrawableTo(iv, Resources, App.Kp2a.GetDb().KpDatabase, pw.IconId, pw.CustomIconUuid); } String title = pw.Strings.ReadSafe(PwDefs.TitleField); var str = new SpannableString(title); if (isExpired) { str.SetSpan(new StrikethroughSpan(), 0, title.Length, SpanTypes.ExclusiveExclusive); } _textView.TextFormatted = str; if (_defaultTextColor == null) _defaultTextColor = _textView.TextColors.DefaultColor; if (_groupActivity.IsBeingMoved(_entry.Uuid)) { int elementBeingMoved = Context.Resources.GetColor(Resource.Color.element_being_moved); _textView.SetTextColor(new Color(elementBeingMoved)); } else _textView.SetTextColor(new Color((int)_defaultTextColor)); String detail = pw.Strings.ReadSafe(PwDefs.UserNameField); if ((_showDetail == false) || (String.IsNullOrEmpty(detail))) { _textviewDetails.Visibility = ViewStates.Gone; } else { var strDetail = new SpannableString(detail); if (isExpired) { strDetail.SetSpan(new StrikethroughSpan(), 0, detail.Length, SpanTypes.ExclusiveExclusive); } _textviewDetails.TextFormatted = strDetail; _textviewDetails.Visibility = ViewStates.Visible; } if ( (!_showGroupFullPath) || (!_isSearchResult) ) { _textgroupFullPath.Visibility = ViewStates.Gone; } else { String groupDetail = pw.ParentGroup.GetFullPath(); var strGroupDetail = new SpannableString (groupDetail); if (isExpired) { strGroupDetail.SetSpan (new StrikethroughSpan (), 0, groupDetail.Length, SpanTypes.ExclusiveExclusive); } _textgroupFullPath.TextFormatted = strGroupDetail; _textgroupFullPath.Visibility = ViewStates.Visible; } }
SpannableString generateCenterSpannableText() { SpannableString s = new SpannableString("MPAndroidChart developed by Philipp Jahoda"); s.SetSpan(new RelativeSizeSpan(1.7f), 0, 14, 0); s.SetSpan(new StyleSpan(TypefaceStyle.Normal), 14, s.Length() - 15, 0); s.SetSpan(new ForegroundColorSpan(Color.Gray), 14, s.Length() - 15, 0); s.SetSpan(new RelativeSizeSpan(.8f), 14, s.Length() - 15, 0); s.SetSpan(new StyleSpan(TypefaceStyle.Italic), s.Length() - 14, s.Length(), 0); s.SetSpan(new ForegroundColorSpan(ColorTemplate.HoloBlue), s.Length() - 14, s.Length(), 0); return s; }
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 override void Decorate(CalendarCellView cellView, DateTime date) { var dateString = date.Day.ToString(); var span = new SpannableString(dateString + "\ntitle"); span.SetSpan(new RelativeSizeSpan(0.5f), 0, dateString.Length, SpanTypes.InclusiveExclusive); cellView.DayOfMonthTextView.TextFormatted = span; }
/// <summary> /// Build the spannable according to the computed text, meaning set the right font, color and size to the text and icon char index /// </summary> /// <param name="computedString"></param> private SpannableString BuildSpannableString(string computedString) { SpannableString span = new SpannableString(computedString); if (!string.IsNullOrEmpty(iconLabel.Icon)) { //set icon span.SetSpan(new CustomTypefaceSpan("fontawesome", iconFont, iconLabel.IconColor.ToAndroid()), computedString.IndexOf(iconLabel.Icon), computedString.IndexOf(iconLabel.Icon) + iconLabel.Icon.Length, SpanTypes.ExclusiveExclusive); //set icon size span.SetSpan(new AbsoluteSizeSpan((int)iconLabel.IconSize,true), computedString.IndexOf(iconLabel.Icon), computedString.IndexOf(iconLabel.Icon) + iconLabel.Icon.Length, SpanTypes.ExclusiveExclusive); } if (!string.IsNullOrEmpty(iconLabel.Text)) { span.SetSpan(new CustomTypefaceSpan("", textFont, iconLabel.TextColor.ToAndroid()), textStartIndex, textStopIndex, SpanTypes.ExclusiveExclusive); span.SetSpan(new AbsoluteSizeSpan((int)iconLabel.FontSize, true), textStartIndex, textStopIndex, SpanTypes.ExclusiveExclusive); } return span; }
/*public override long GetItemId (int position) { return _Posts [position].Id; }*/ public static SpannableString BuildBackgroundColorSpan(SpannableString spannableString, String text, String searchString, Color color) { int indexOf = text.ToUpperInvariant().IndexOf(searchString.ToUpperInvariant()); try { spannableString.SetSpan(new BackgroundColorSpan(color), indexOf, (indexOf + searchString.Length),SpanTypes.ExclusiveExclusive); } catch (Exception e) { } return spannableString; }
private void Render(Marker marker, View view) { int badge; // Use the equals() method on a Marker to check for equals. Do not use ==. if (marker.Equals(parent.mBrisbane)) { badge = Resource.Drawable.badge_qld; } else if (marker.Equals(parent.mAdelaide)) { badge = Resource.Drawable.badge_sa; } else if (marker.Equals(parent.mSydney)) { badge = Resource.Drawable.badge_nsw; } else if (marker.Equals(parent.mMelbourne)) { badge = Resource.Drawable.badge_victoria; } else if (marker.Equals(parent.mPerth)) { badge = Resource.Drawable.badge_wa; } else { // Passing 0 to setImageResource will clear the image view. badge = 0; } ((ImageView) view.FindViewById (Resource.Id.badge)).SetImageResource (badge); String title = marker.Title; TextView titleUi = ((TextView) view.FindViewById (Resource.Id.title)); if (title != null) { // Spannable string allows us to edit the formatting of the text. SpannableString titleText = new SpannableString (title); SpanTypes st = (SpanTypes) 0; // FIXME: this somehow rejects to compile //titleText.SetSpan (new ForegroundColorSpan(Color.Red), 0, titleText.Length, st); titleUi.TextFormatted = (titleText); } else { titleUi.Text = (""); } String snippet = marker.Snippet; TextView snippetUi = ((TextView) view.FindViewById(Resource.Id.snippet)); if (snippet != null) { SpannableString snippetText = new SpannableString(snippet); snippetText.SetSpan(new ForegroundColorSpan(Color.Magenta), 0, 10, 0); snippetText.SetSpan(new ForegroundColorSpan(Color.Blue), 12, 21, 0); snippetUi.TextFormatted = (snippetText); } else { snippetUi.Text = (""); } }
public static void SetTextWithRouble(this TextView label, string text, RoubleType roubleType) { var textFormatted = new SpannableString(text + Roubles.GetRoubleSymbFor(roubleType)); textFormatted.SetSpan(RoubleSpan, textFormatted.Length() - 1, textFormatted.Length(), SpanTypes.ExclusiveExclusive); label.TextFormatted = textFormatted; }