Xamarin.Android hyperlink in middle of text not working

167 Views Asked by At

Goal: Have a word in the middle of a sentence be a hyperlink that opens the website in a browser

What's happening: It looks like a hyperlink, but nothing happens when I click

What I've tried:

  • I tried making it an intent, that worked to make it clickable, but it made the entire sentence clickable.
  • Also, I then switched to using the Html.FromHtml method.

C#:

string Content = "<span>Please navigate to <a href='https://www.website.com'>HERE</a> to register</span>";
lblTESTSystem.TextFormatted = Html.FromHtml(Content); //lblTESTSystem.SetText(Html.FromHtml(Content, FromHtmlOptions.ModeLegacy), TextView.BufferType.Spannable);

What the above code looks like:

enter image description here

Alternate/first C# code that made entire sentence clickable:

//lblTESTSystem.Click += (sender, eventArgs) => 
//{
//    var uri = Android.Net.Uri.Parse("https://www.website.com");
//        var intent = new Intent(Intent.ActionView, uri);
//        StartActivity(intent);
//};
1

There are 1 best solutions below

1
Guangyu Bai - MSFT On

You can add the WebView in the xaml page then bind a html file to the WebView.source.

In the MainPage.xaml, you can add the code to the target page.

<WebView x:Name="webView" WidthRequest="1000" HeightRequest="1000" /> 

In the MainPage.xaml.cs

 public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

            webView.Source = "file:///android_asset/name.html";
        }
    }

Then Create the name.html file in the target file package.

 <html>
    <body>
       <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>

       <span>Please navigate to <a href='https://www.website.com'>HERE</a> to register</span>

    </body>
 </html>