TextView
Компонент TextView предназначен для отображения текста без возможности редактирования его пользователем, что видно из его названия (Text — текст, view — просмотр).
Находится в разделе Texts.
TextView — один из самых используемых компонентов. С его помощью пользователю удобнее ориентироваться в программе. По сути, это как таблички: Руками не трогать, По газону не ходить, Вход с собаками воспрещен, Часы работы с 9.00 до 18.00 и т.д., и служит для представления пользователю описательного текста.
Для отображения текста в TextView в файле разметки используется атрибут android:text, например:
android:text="Погладь кота, . "
Такой подход является нежелательным. Рекомендуется всегда использовать текстовые ресурсы. В будущем эта привычка позволит вам обеспечить многоязыковую поддержку:
android:text="@string/hello"
Программная установка текста
Программно текст можно задать методом setText():
// Инициализируем компонент TextView textView = findViewById(R.id.textView); // задаём текст textView.setText("Hello Kitty!"); // или с использованием текстовых ресурсов textView.setText(R.string.hello);
Атрибуты
android:textsize размер текста. При установке размера текста используется несколько единиц измерения: px (пиксели), dp, sp, in (дюймы), pt, mm. Для текстов рекомендуется использовать sp: android:textSize=»48sp», аналог — метод setTextSize() android:textstyle стиль текста. Используются константы: normal, bold, italic. Например, android:textStyle=»bold» выводит текст жирным android:textcolor цвет текста. Используются четыре формата в шестнадцатеричной кодировке: #RGB; #ARGB; #RRGGBB; #AARRGGBB, где R, G, B — соответствующий цвет, А — прозрачность (alpha-канал). Значение А, установленное в 0, означает прозрачность 100%.
Для всех вышеперечисленных атрибутов в классе TextView есть соответствующие методы для чтения или задания соответствующих свойств.
Программно установим размеры текста при помощи setTextSize() с различными единицами измерения.
// 20 DIP (Device Independent Pixels) textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); // 0.5 inch textView.setTextSize(TypedValue.COMPLEX_UNIT_IN, 0.5f); // 10 millimeter textView.setTextSize(TypedValue.COMPLEX_UNIT_MM, 10); // 30 points textView.setTextSize(TypedValue.COMPLEX_UNIT_PT, 30); // 30 raw pixels textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 30); // 30 scaled pixels textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);
По умолчанию у компонентов TextView отсутствует фоновый цвет. Чтобы задать цвет, укажите значение Drawable для атрибута android:background. В качестве значения Drawable может использоваться изображение или XML-представление фигуры, включающий ресурс Drawable (поместить в папку res/drawable).
Программная установка фона
В некоторых случаях программисты из-за невнимательности неправильно меняют фон элемента программным способом и удивляются, почему ничего не работает.
Предположим, у вас определён в ресурсах зелёный цвет:
#337700
Следующий код будет ошибочным:
textview.setBackgroundColor(R.color.tvBackground); // не работает
Нужно так (два варианта):
textView.setBackgroundResource(R.color.tvBackground); // первый вариант textView.setBackgroundColor(getResources().getColor(R.color.tvBackground)); // второй вариант
Реагируем на событие onClick
Если вы хотите, чтобы TextView обрабатывал нажатия (атрибут android:onClick), то не забывайте также использовать в связке атрибут android:clickable=»true». Иначе работать не будет!
Многострочный текст
Если вы хотите создать многострочный текст в TextView, то используйте символы \n для переноса строк.
Например, в ресурсах:
У лукоморья дуб зелёный;\n Златая цепь на дубе том:\n И днём и ночью кот учёный\n Всё ходит по цепи кругом;\n Идёт направо - песнь заводит,\n Налево - сказку говорит.
Обратите внимание, что в тексте также применяется простое форматирование.
Также перенос на новую строку можно задать в коде:
textView.setText("Первая строка \nВторая строка \nТретья строка");
Увеличиваем интервалы между строками
Вы можете управлять интервалом между соседними строчками текста через атрибут android:lineSpacingMultiplier, который является множителем. Установите дробное значение меньше единицы, чтобы сократить интервал или больше единицы, чтобы увеличить интервал между строками.
android:lineSpacingMultiplier="0.8"
Бой с тенью
Чтобы оживить текст, можно дополнительно задействовать атрибуты для создания эффектов тени: shadowColor, shadowDx, shadowDy и shadowRadius. С их помощью вы можете установить цвет тени и ее смещение. Во время установки значений вы не увидите изменений, необходимо запустить пример в эмуляторе или на устройстве. В следующем примере я создал тень красного цвета со смещением в 2 пикселя по вертикали и горизонтали. Учтите, что для смещения используются единицы px (пиксели), единицы dp не поддерживаются.

Программный эквивалент — метод public void setShadowLayer (float radius, float dx, float dy, int color):
TextView textShadow = (TextView)findViewById(R.id.hello); textShadow.setShadowLayer( 5f, //float radius 10f, //float dx 10f, //float dy 0xFFFFFFFF //int color );
Создание ссылок автоматом
У TextView есть ещё два интересных свойства Auto link (атрибут autoLink) и Links clickable (атрибут linksClickable), которые позволяют автоматически создавать ссылки из текста.
Выглядит это следующим образом. Предположим, мы присвоим элементу TextView текст Мой сайт: developer.alexanderklimov.ru и применим к нему указанные свойства.
При этом уже на этапе разработки вы увидите, что строка адреса сайта после слов Мой адрес: стала ссылкой. Если вы запустите приложение и нажмете на ссылку, то откроется браузер с указанным адресом. Вам даже не придется писать дополнительный код. Аналогично, если указать номер телефона (параметр phone), то запустится звонилка.
У ссылки есть интересная особенность — при длительном нажатии на ссылку появляется диалоговое окно, позволяющее скопировать ссылку в буфер обмена.
Атрибут autoLink позволяет комбинировать различные виды ссылок для автоматического распознавания: веб-адрес, email, номер телефона.

Цвет ссылки можно поменять через свойство Text color link (XML-атрибут textColorLink), а программно через метод setTextLinkColor().
Программно можно установить ссылки на текст через класс Linkify:
TextView tvDisplay = (TextView)findViewById(R.id.tvDisplay); String data = "" + "Пример использования Linkify для создания ссылок в тексте.\n" + "\n" + "URL: http://developer.alexanderklimov.ru/ \n" + "Email: [email protected] \n" + "Телефон: (495)-458-58-29 \n" + "Адрес: 10110 ул.Котовского, г.Мышкин \n" + "\n" + "Классно получилось?"; if(tvDisplay != null)

Кроме константы ALL, можно также использовать Linkify.EMAIL_ADDRESSES, Linkify.MAP_ADDRESSES, Linkify.PHONE_NUMBERS. К сожалению, русские адреса не распознаются. В моём случае индекс был распознан как телефонный номер, а город и улица не стали ссылкой.
В таких случаях придётся самостоятельно добавить ссылки в текстах. Например, определим ссылку в ресурсе:
Присвоим созданный ресурс тексту в TextView и запустим пример. Сам текст будет выглядеть как ссылка, но реагировать не будет. Чтобы исправить данную проблему, добавим код:
TextView textView = (TextView) findViewById(R.id.textView); textView.setMovementMethod(LinkMovementMethod.getInstance());
Ссылки в тексте выглядят не совсем удобными. Есть отдельная библиотека, которая улучшает функциональность. Описание проблем и ссылка на библиотеку есть в статье A better way to handle links in TextView — Saket Narayan.
Совет: Используйте полупрозрачность с умом
Если вам нужно установить текст полупрозрачным, то не используйте атрибут android:alpha:
Дело в том, что такой подход затрачивает много ресурсов при перерисовке.
Атрибут textColor позволяет установить полупрозрачность без потери производительности:
Выделить текст для копирования
По умолчанию, текст в TextView нельзя выделить для копирования. Но в API 11 появилась такая возможность, которая может пригодиться. Делается либо при помощи XML-атрибута android:textIsSelectable, либо через метод setTextIsSelectable().
Добавьте в разметку два компонента TextView и одно текстовое поле EditText для вставки скопированного текста. У первой текстовой метки установим возможность выделения текста декларативно.
Для второго компонента возможность выделения создадим программно.
TextView secondTextView = (TextView) findViewById(R.id.textView2); secondTextView.setTextIsSelectable(true);
Сделайте долгий тап на тексте в любом TextView. Увидите стандартные ползунки для выбора длины текста. Скопируйте текст, сделайте длинный тап в EditText и вставьте текст.
Стили
Выводим разделитель под текстом.
Kotlin Android TextView and EditText
Android TextView is a user interface which displays the text to the user.
A simple XML code of TextView in a layout is shown below.
We can get and modify the content of text view defined in the XML layout in Kotlin class file as:
The EditText is a user interface which is used for entering and changing the text. While using edit text in XML layout, we must specify its inputType attribute which configures the keyboard according to input type mention.
The simple XML code of EditText in a layout is shown below.
We can get and modify the content of edit text defined in the XML layout in Kotlin class file as:
Kotlin Android TextView and ExitText Example
In this example, we input the text value in ExitText and display its value in the TextView on clicking the Button.
We are also watching the changes made over EditText using addTextChangedListener () method and TextWatcher interface.
activity_main.xml
In the activity_main.xml file add the following code.
MainActivity.kt
Add the following code in MainActivity.kt class. In this class, we are getting the value of the edit text and display it in text view by clicking the button. At the same time, we are also watching the changes made over EditText using addTextChangedListener () method and TextWatcher interface. To learn more about TextWatcher refers to https://www.javatpoint.com/android-edittext-with-textwatcher
Output:
Next Topic #

For Videos Join Our Youtube Channel: Join Now
Feedback
- Send your Feedback to [email protected]
Help Others, Please Share

Learn Latest Tutorials
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
Python Design Patterns
![]()
![]()
![]()
Preparation




Trending Technologies
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
B.Tech / MCA
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter

Android – Kotlin Android Studio Warning “Do not concatenate text displayed with setText. Use resource string with placeholders.”
The warning is gone but I got problems, first the result is integer which is not what I expected. It should be double. Second, adding the function format in getString will stop the program with «Unexpected Error…» message on the screen.
How can I solve this problem?
Best Solution
If you have string with some placeholders like:
Your price: %d
First you have to read this value and next fill it
JAVA
String text = getString(R.string.price_string, 2.5);
KOTLIN
val text = getString(R.string.price_string, 2.5)
or in «longer» way:
JAVA:
// Read text String priceString = getString(R.string.price_string); // Fill it String output = String.format(priceString, 2.5);
KOTLIN
// Read text val priceString = getString(R.string.price_string) // Fill it val output = String.format(priceString, 2.5) // or val output = priceString.format(2.5)
Related Solutions
Android – getFragmentManager returning null pointer exception
The casting problem can be solved by
mGoogleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
If you want map inside a fragment you need to use MapView or you need to extend SupportMapFragment .
You can refer the below
Android TextView : “Do not concatenate text displayed with setText”
Resource has the get overloaded version of getString which takes a varargs of type Object : getString(int, java.lang.Object. ). If you setup correctly your string in strings.xml, with the correct place holders, you can use this version to retrieve the formatted version of your final String. E.g.
Hello, %1$s! You have %2$d new messages.
using getString(R.string.welcome_message, «Test», 0);
android will return a String with
"Hello Test! you have 0 new messages"
About setText(«» + name);
Your first Example, prodNameView.setText(«» + name); doesn’t make any sense to me. The TextView is able to handle null values. If name is null, no text will be drawn.
Related Question
- Java – Do not concatenate text displayed with setText. Use resource string with placeholders
- Android – Outdated Kotlin Runtime warning in Android Studio
Android TextView and setText Dynamically example in Kotlin
Android TextView is a user interface element that shows the text (label) to users in the application. You can change TextView dynamically (programmatically). View class is the parent class of the android.widget.TextView. TextView can Create by declaring it inside a layout XML file or by instantiating it programmatically.

Android TextView Attributes
Here we are explaining the some attribute of TextView.
android:id
This is the ID which uniquely identifies the control.
android:id="@+id/textView"
android:textAllCaps

Set all the text in ALL CAPS.
android:textColor

Set the Text color of TextView widget android.
TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Color TextView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" android:textColor="@color/colorAccent"/>
android:textSize

Set the Size of the text, use SP unit to set size.
android:textStyle

Style (normal, bold, italic, bold|italic) for the TextView.
For more, you can check Android’s official documentation of a complete list of attributes and related methods, Uses to change these attributes are run time or make as per app requirements.
Let’s Build a Complete Example of Android TextView:
In this example will learn to change TextView dynamically, change color, setText, change Text Size, Change the style and Capitalize TextView.
Step 1. Create new project “ Build Your First Android App in Kotlin “
Step 2. Add the following code in “activity_main.xml” resource file
Step 3. Open the “MainActivity.kt” and add following code
Here Button have even on click event , where TextView is changing text dynamically.
package `in`.eyehunt.androidtextview import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) >// Dynamically text change - on click button fun changeText(view : View) < textView5.setText("Hello I am dynamic text") >>
Step 4. Now Run the application, in emulator or On you android device
Output screenshot Android TexView example :

Download source code Android TextView in kotlin
Note: This example (Project) is developed in Android Studio 3.1.3. Tested on Android 9 ( Android-P), compile SDK version API 26: Android 8.0 (Oreo)
MinSdkVersion=”15″
TargetSdkVersion=”27″
Coding in Kotlin
