Android textview html link click

The TextView is a widget in Android that allows you to display text to the user. It is also possible to use the Android TextView widget to create a hyperlink which can load a web page in a mobile web browser when clicked.

To create a clickable hyperlink in your Android app using the TextView widget follow the steps below.

  1. Create a new String resource in the strings.xml resource file representing the text to be placed inside the TextView
  2. In your String resource use HTML markup to insert the hyperlink using an anchor tag
  3. Add a TextView in the layout of your Activity or Fragment and use the android:text attribute on the TextView to reference the String resource containing the hyperlink
  4. In your Activity or Fragment class use the setMovementMethod(…) on the TextView to enable the hyperlink

In the article below I will include Java and Kotlin code samples that show how to create a hyperlink using the Android TextView following the steps listed above.

I have also included some additional instructions along with code samples written in Kotlin for using links in Android apps in different ways such as:

  • How to Change the Hyperlink Text Color in a TextView
  • How to Create a Clickable Link to a Website Using a Button in Android
  • How to Create a Clickable Link to Another Activity in a TextView

Below is a screenshot of an Android app we will be building in this tutorial for creating a hyperlink using the Android TextView widget. When the hyperlink is selected the app will open a mobile web browser and navigate the user to the website https://learntodroid.com

In this tutorial will cover the following steps for creating a hyperlink using the Android TextView widget.

  1. Creating a String Resource for the Hyperlink in HTML Markup
  2. Creating an Activity Layout File with a TextView
  3. Enabling the TextView Hyperlink in the Activity or Fragment Class

I will include code excerpts embedded into this tutorial. For step 3, I have included code samples for both Kotlin and Java.

I have created a video tutorial embedded below on how to create a hyperlink inside a TextView in an Android app. The code written in this video tutorial is also available on GitHub.

The first part of this tutorial for creating a hyperlink using the Android TextView widget will require you to add a new String Resource into the strings.xml file that will represent the text that will be used by the TextView for the hyperlink.

You will need to use HTML markup when writing your hyperlink in your resource file. This means you will need to use an anchor tag and use the href attribute on the anchor tag to capture the URI. Inside the anchor tag you will also need to add some text that will be displayed as a hyperlink to the user in the app.

Читайте также:  Проблемы с внутренней памятью андроид

You can also add a description to the link above or next to the link by adding some text outside of the anchor text in the String Resource. In my example I have also added a new line between my description of the link and the clickable link.

See the code sample of the strings.xml resource file below containing the hyperlink String resource.

Creating an Activity Layout File with a TextView

The next step in this tutorial will involve setting up the layout file for your Activity or Fragment that will contain the hyperlink TextView.

When you are creating the TextView in the layout file you will need to take care of a few things.

  1. Give the TextView an id using the “android:id” attribute so that you can reference it in the next part of the tutorial in your Activity or Fragment class
  2. Use the “android:text” attribute to reference the String resource you have created above for your hyperlink
  3. If you the text shown in the TextView is going to spill over one row consider centering the TextView by setting the “android:textAlignment” attribute to the value of “center”

See the code sample of the activity_main.xml layout resource file below containing a TextView to be shown inside a ConstraintLayout.

The final step of this tutorial involves enabling the hyperlink to be clickable in your Activity or Fragment class by using the setMovementMethod(…) on the TextView.

The setMovementMethod(…) takes a MovementMethod as a parameter. In this tutorial we will be making use of the LinkMovementMethod allow the hyperlink to be clickable and to handle the launching of the web browser and navigation to the link in the browser when selected.

Java Example

See the code sample of the MainActivity.java Activity class file below showing the enabling of the hyperlink using setMovementMethod(…)

Kotlin Example

See the code sample of the MainActivity.kt Activity class file below showing the enabling of the hyperlink using setMovementMethod(…)

By default the hyperlinks shown in your Android TextView widget will be displayed in a dark pink text color with an underline.

You can change the default color of the text of the hyperlink using the setLinkTextColor(…) method on the TextView.

See the code sample of the MainActivity.kt Activity class file below setting the color of the hyperlink in the TextView to blue using setLinkTextColor(…)

See a screenshot showing the hyperlink inside the TextView in blue using the code from the excerpt above.

You can also use a Button widget in Android to load a web page in the mobile browser when clicked.

To do this you will need to make use of an Intent and use the startActivity(…) method to launch an Intent when the Button is clicked.

See the code sample of the MainActivity.kt Activity class file below showing how to use a Button to launch a web browser on the device at a given URI when clicked.

I have written another blog post on this website about how to switch between Activities in Android using an Intent. To learn more about this including an example using a Button to switch between Activities using an Intent check out the article below.

Читайте также:  Audio recorder 4pda android

If you want to use a TextView instead of a Button to create a link to another Activity you can take the code samples from that lesson and replace the Button with a TextView. You will need to style the text shown in the TextView to look like a hyperlink by setting the text color to blue and adding an underline. There you will need to add an OnClickListener to create the Intent when the TextView is selected.

See the code excerpt from the IntentNavigationActivity.kt Activity class file below which shows setting the text color of the TextView to blue and adding an on click listener to switch to the MainActivity using an Intent when the TextView is clicked.

See the code sample of the activity_intent_navigation.xml layout resource file below containing a TextView to be shown inside a ConstraintLayout.

See the code sample of the strings.xml resource file below containing String Resource for the activity link which is underlined using HTML markup.

You will ensure need to use you have included references to all of the Activities you will be using and navigating between in your manifest file. This is done using the activity tag inside the application tag of the Android Manifest file.

Loading…

Источник

Android TextView с кликабельными ссылками: как захватить клики?

У меня есть TextView, который отображает базовый HTML, содержащий 2 + ссылки. Мне нужно захватить клики по ссылкам и открыть ссылки-в моем собственном внутреннем WebView (не в браузере по умолчанию.)

наиболее распространенный метод обработки рендеринга ссылок выглядит следующим образом:

однако это заставляет ссылки открываться во внутреннем веб-браузере по умолчанию(показывая » полное действие с помощью. » диалог.)

Я попытался реализовать onClickListener, который правильно запускается при нажатии ссылки, но я не знаю, как определить, какая ссылка была нажата.

кроме того, я попытался создать пользовательский класс LinkMovementMethod и реализовать onTouchEvent.

пример решения

Я придумал решение который анализирует ссылки из строки HTML и делает их кликабельными, а затем позволяет вам отвечать на URL-АДРЕС.

7 ответов

на основе еще один ответ, вот функция setTextViewHTML (), которая анализирует ссылки из строки HTML и делает их кликабельными, а затем позволяет вам отвечать на URL.

Это можно просто решить с помощью Spannable String.То, что вы действительно хотите сделать (бизнес-требование), мне немного неясно, поэтому следующий код не даст точного ответа на вашу ситуацию, но я уверен, что он даст вам некоторое представление, и вы сможете решить свою проблему на основе следующего кода.

Как и вы, я также получаю некоторые данные через HTTP-ответ, и я добавил некоторые дополнительные подчеркнутый текст в моем случае «больше» и этот подчеркнутый текст откроет веб-браузер на Click event.Надеюсь, это поможет вам.

вы сделали следующее:

вы пробовали в обратном порядке, как показано ниже?

у меня была та же проблема, но много текста, смешанного с несколькими ссылками и электронными письмами. Я думаю, что использование «autoLink» — это более простой и чистый способ сделать это:

Вы можете установить Linkify.EMAIL_ADDRESSES или Linkify.WEB_URLS, если есть только один из них вы хотите использовать или установить из XML-макета

доступные варианты: нет, веб, электронная почта, телефон, карта, все

более чистое и лучшее решение, используя native библиотека Linkify.

решение

я реализовал небольшой класс, с помощью которого вы можете обрабатывать длинные клики по самому TextView и нажимать на ссылки в TextView.

планировка

TextViewClickMovement.java

использование

ссылки

надеюсь, это helops! Вы можете найти код здесь.

Im, используя только textView, и установить диапазон для url и дескриптора нажмите.

Читайте также:  Андроид сообщение при входящем звонке

Я нашел здесь очень элегантное решение, без linkify-в соответствии с этим я знаю, какую часть строки Я хочу linkify

и использование: linkify (yourTextView, urlString, context)

Источник

Android TextView-LinkBuilder

Insanely easy way to create clickable links within a TextView .

While creating Talon for Twitter, one of the most difficult things I encountered was creating these clickable links based on specific text. Luckily, I have made it easy for anyone to apply this type of style to their TextView ‘s.

Similar to how all the big players do it (Google+, Twitter, cough Talon cough), this library allows you to create clickable links for any combination of String s within a TextView .

  • Specify long and short click actions of a specific word within your TextView
  • Provide user feedback by highlighting the text when the user touches it
  • Match single String s or use a regular expression to set clickable links to any text conforming to that pattern
  • Change the color of the linked text
  • Change the color of the linked text when the user touches it
  • Modify the transparency of the text’s highlighting when the user touches it
  • Set whether or not you want the text underlined
  • Set whether or not you want the text bold
  • Default link color from an activity theme

The main advantage to using this library over TextView ‘s autolink functionality is that you can link anything, not just web address, emails, and phone numbers. It also provides color customization and touch feedback.

There are two ways to use this library:

As a Gradle dependency

This is the preferred way. Simply add:

to your project dependencies and run gradle build or gradle assemble .

As a library project

Download the source code and import it as a library project in Eclipse. The project is available in the folder library. For more information on how to do this, read here.

Functionality can be found in the Kotlin example’s MainActivity. For Java check JavaMainActivity.

For a list of regular expressions that I use in Talon, you can go here

You can also create a CharSequence instead of creating and applying the links directly to the TextView . Do not forget to set the movement method on your TextView ‘s after you have applied the CharSequence , or else the links will not be clickable.

If you would like to set the default text color for links without inputting it manually on each Link object, it can be set from the activity theme.

The library is built on Kotlin, so you get some extension methods that you can use to apply the links to the TextView , instead of creating the builder.

Usage with ListView.OnItemClickListener

By default, LinkBuilder will consume all the touch events on your TextView . This means that ListView.OnItemClickListener will never get called if you try to implement it. The fix for this is to implement the LinkConsumableTextView rather than the normal TextView in your layouts.

My LinkConsumableTextView will only consume touch events if you have clicked the link within the TextView . Otherwise, it will defer the touch event to the parent, which allows you to use ListView.OnItemClickListener method.

Please fork this repository and contribute back using pull requests. Features can be requested using issues. All code, comments, and critiques are greatly appreciated.

The full changelog for the library can be found here.

Источник

Оцените статью