Label hyperlink

Ángel Rubén Valdeolmos Carmona 586 Reputation points
2021-09-23T14:26:18.253+00:00

I get a long string with text and it may contain some URl in that text, how can I make that url clickable? I don't get any html, just string.

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,289 questions
0 comments No comments
{count} votes

Accepted answer
  1. Borisoprit 371 Reputation points
    2021-09-23T18:01:23.3+00:00

    Something like This ?

    134716-img-3446.jpg

    Make a Class with the name LinksLabel

    public class LinksLabel : Label

    {  
        public static BindableProperty LinksTextProperty = BindableProperty.Create(nameof(LinksText), typeof(string), typeof(LinksLabel), propertyChanged: OnLinksTextPropertyChanged);  
        [Obsolete]  
        private readonly ICommand _linkTapGesture = new Command<string>((url) => Device.OpenUri(new Uri(url)));  
    
        public string LinksText  
        {  
            get => GetValue(LinksTextProperty) as string;  
            set => SetValue(LinksTextProperty, value);  
        }  
    
        private void SetFormattedText()  
        {  
            var formattedString = new FormattedString();  
    
            if (!string.IsNullOrEmpty(LinksText))  
            {  
                var splitText = LinksText.Split(' ');  
    
                foreach (string textPart in splitText)  
                {  
                    var span = new Span { Text = $"{textPart} " };  
    
                    if (IsUrl(textPart)) // a link  
                    {  
                        span.TextColor = Color.DeepSkyBlue;  
                        span.GestureRecognizers.Add(new TapGestureRecognizer  
                        {  
                            Command = _linkTapGesture,  
                            CommandParameter = textPart  
                        });  
                    }  
    
                    formattedString.Spans.Add(span);  
                }  
            }  
    
            this.FormattedText = formattedString;  
        }  
    
        private bool IsUrl(string input)  
        {  
            return Uri.TryCreate(input, UriKind.Absolute, out var uriResult) &&  
              (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);  
        }  
    
        private static void OnLinksTextPropertyChanged(BindableObject bindable, object oldValue, object newValue)  
        {  
            var linksLabel = bindable as LinksLabel;  
            linksLabel.SetFormattedText();  
        }  
    }  
    

    Add to the Class

    using System.Windows.Input;

    using Xamarin.Forms;

    Then in Xaml

    <StackLayout>

        <custom:LinksLabel  
            HorizontalTextAlignment="Center"  
            LinksText="This Xamarin.Forms Forums question can be visited at https://forums.xamarin.com/discussion/161082/make-multiple-links-in-labels-clickable#latest but Google only at https://www.google.com/"  
            TextColor="DarkGray" />  
    
    </StackLayout>  
    

1 additional answer

Sort by: Most helpful
  1. JarvanZhang 23,936 Reputation points
    2021-09-24T01:32:09.257+00:00

    Hello Angelru-4290,​

    Welcome to our Microsoft Q&A platform!

    how can I make that url clickable? I don't get any html, just string.

    To display the Hyperlinks as string, try using Formatted text to display the url separately and adding tap gesture to the 'link' to achieve the loading function. Here is the sample code, you could refer to it.

       <Label>  
           <Label.FormattedText>  
               <FormattedString>  
                   <Span Text="Alternatively, click " />  
                   <Span Text="this link"  
                                 TextColor="Blue"  
                                 TextDecorations="Underline">  
                       <Span.GestureRecognizers>  
                           <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"  
                                                 CommandParameter="https://learn.microsoft.com/xamarin/" />  
                       </Span.GestureRecognizers>  
                   </Span>  
                   <Span Text=" to view Xamarin documentation." />  
               </FormattedString>  
           </Label.FormattedText>  
       </Label>  
         
         
       private async void TapGestureRecognizer_Tapped(object sender, EventArgs e)  
       {  
           var url = (e as TappedEventArgs).Parameter as string;  
           await Launcher.OpenAsync(url);  
       }  
         
       //you can also use tap command as below:  
        public ICommand TapCommand => new Command<string>(async (url) => await Launcher.OpenAsync(url));  
    

    For more details, please refer to the docs:
    https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/text/label#hyperlinks
    https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/text/label#formatted-text

    Best Regards,

    Jarvan Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.