Android textview with link

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.

Читайте также:  Переводчик promt offline 4pda android

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.

Читайте также:  Включение экрана при поднятии android one

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.

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…

Источник

TextView

Компонент TextView предназначен для отображения текста без возможности редактирования его пользователем, что видно из его названия (Text — текст, view — просмотр).

Находится в разделе Texts.

TextView — один из самых используемых компонентов. С его помощью пользователю удобнее ориентироваться в программе. По сути, это как таблички: Руками не трогать, По газону не ходить, Вход с собаками воспрещен, Часы работы с 9.00 до 18.00 и т.д., и служит для представления пользователю описательного текста.

Для отображения текста в TextView в файле разметки используется атрибут android:text, например:

Такой подход является нежелательным. Рекомендуется всегда использовать текстовые ресурсы. В будущем эта привычка позволит вам обеспечить многоязыковую поддержку:

Программная установка текста

Программно текст можно задать методом setText():

Атрибуты

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

Программно установим размеры текста при помощи setTextSize() с различными единицами измерения.

По умолчанию у компонентов TextView отсутствует фоновый цвет. Чтобы задать цвет, укажите значение Drawable для атрибута android:background. В качестве значения Drawable может использоваться изображение или XML-представление фигуры, включающий ресурс Drawable (поместить в папку res/drawable).

Программная установка фона

В некоторых случаях программисты из-за невнимательности неправильно меняют фон элемента программным способом и удивляются, почему ничего не работает.

Предположим, у вас определён в ресурсах зелёный цвет:

Следующий код будет ошибочным:

Нужно так (два варианта):

Реагируем на событие onClick

Если вы хотите, чтобы TextView обрабатывал нажатия (атрибут android:onClick), то не забывайте также использовать в связке атрибут android:clickable=»true». Иначе работать не будет!

Многострочный текст

Если вы хотите создать многострочный текст в TextView, то используйте символы \n для переноса строк.

Например, в ресурсах:

Читайте также:  Лего ниндзяго тень ронина для андроид

Обратите внимание, что в тексте также применяется простое форматирование.

Также перенос на новую строку можно задать в коде:

Увеличиваем интервалы между строками

Вы можете управлять интервалом между соседними строчками текста через атрибут android:lineSpacingMultiplier, который является множителем. Установите дробное значение меньше единицы, чтобы сократить интервал или больше единицы, чтобы увеличить интервал между строками.

Бой с тенью

Чтобы оживить текст, можно дополнительно задействовать атрибуты для создания эффектов тени: shadowColor, shadowDx, shadowDy и shadowRadius. С их помощью вы можете установить цвет тени и ее смещение. Во время установки значений вы не увидите изменений, необходимо запустить пример в эмуляторе или на устройстве. В следующем примере я создал тень красного цвета со смещением в 2 пикселя по вертикали и горизонтали. Учтите, что для смещения используются единицы px (пиксели), единицы dp не поддерживаются.

Программный эквивалент — метод public void setShadowLayer (float radius, float dx, float dy, int color):

Создание ссылок автоматом

У TextView есть ещё два интересных свойства Auto link (атрибут autoLink) и Links clickable (атрибут linksClickable), которые позволяют автоматически создавать ссылки из текста.

Выглядит это следующим образом. Предположим, мы присвоим элементу TextView текст Мой сайт: developer.alexanderklimov.ru и применим к нему указанные свойства.

При этом уже на этапе разработки вы увидите, что строка адреса сайта после слов Мой адрес: стала ссылкой. Если вы запустите приложение и нажмете на ссылку, то откроется браузер с указанным адресом. Вам даже не придется писать дополнительный код. Аналогично, если указать номер телефона (параметр phone), то запустится звонилка.

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

Атрибут autoLink позволяет комбинировать различные виды ссылок для автоматического распознавания: веб-адрес, email, номер телефона.

Цвет ссылки можно поменять через свойство Text color link (XML-атрибут textColorLink), а программно через метод setTextLinkColor().

Программно можно установить ссылки на текст через класс Linkify:

Кроме константы ALL, можно также использовать Linkify.EMAIL_ADDRESSES, Linkify.MAP_ADDRESSES, Linkify.PHONE_NUMBERS. К сожалению, русские адреса не распознаются. В моём случае индекс был распознан как телефонный номер, а город и улица не стали ссылкой.

В таких случаях придётся самостоятельно добавить ссылки в текстах. Например, определим ссылку в ресурсе:

Присвоим созданный ресурс тексту в TextView и запустим пример. Сам текст будет выглядеть как ссылка, но реагировать не будет. Чтобы исправить данную проблему, добавим код:

Ссылки в тексте выглядят не совсем удобными. Есть отдельная библиотека, которая улучшает функциональность. Описание проблем и ссылка на библиотеку есть в статье A better way to handle links in TextView — Saket Narayan.

Совет: Используйте полупрозрачность с умом

Если вам нужно установить текст полупрозрачным, то не используйте атрибут android:alpha:

Дело в том, что такой подход затрачивает много ресурсов при перерисовке.

Атрибут textColor позволяет установить полупрозрачность без потери производительности:

Выделить текст для копирования

По умолчанию, текст в TextView нельзя выделить для копирования. Но в API 11 появилась такая возможность, которая может пригодиться. Делается либо при помощи XML-атрибута android:textIsSelectable, либо через метод setTextIsSelectable().

Добавьте в разметку два компонента TextView и одно текстовое поле EditText для вставки скопированного текста. У первой текстовой метки установим возможность выделения текста декларативно.

Для второго компонента возможность выделения создадим программно.

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

Источник

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