- 400+ Android & Flutter Code
- Saturday, January 3, 2015
- How to change TextView background color in android
- Set TextView background color programmatically
- Relative Layout Background Color And Image Example In Android Studio
- TextView
- Программная установка текста
- Атрибуты
- Программная установка фона
- Реагируем на событие onClick
- Многострочный текст
- Увеличиваем интервалы между строками
- Бой с тенью
- Создание ссылок автоматом
- Совет: Используйте полупрозрачность с умом
- Выделить текст для копирования
- Android TextView Decoration Tutorial
- TextView
- Typeface
- Textstyle
- Text size and Text Color
- Font family
- Text alignment
- Text shadow
- Non Breaking Sentence
- Gradient
- Clickable span
- Background Image
- Conclusion
400+ Android & Flutter Code
Example code for android + flutter app developers.
Saturday, January 3, 2015
How to change TextView background color in android
TextView display text on android application. android developer can change TextView background color both programmatically at run time in java file and statically by declarative syntax in xml layout file or xml xml resource file.
the following example code demonstrate us how can we set or change the TextView background color by declarative syntax. in this example we did not make any changes on java file, so we does not include java file here.
in this exampe code we include few TextView widgets. we define their background color by various way. the simple way to define TextView background color is its android:background attribute. we can assign a Hexadecimal color string for this attribute to generate TextView background color.
Hexadecimal color is specified with an RGB value and optional alpha channel. in this example code we uses the following hexadecimal color format to define Textview background color, those are #RGB, #ARGB, #RRGGBB and #AARRGGBB. in this hexadecimal color format ‘A’ describe alpha channel, ‘R’ describe red channel, ‘G’ describe green channel and ‘B’ describe blue channel.
Color is a simple resource which we can reference using the value provided in the name attribute not the name of xml file. so we can combine color resources with other simple resources in a single xml file. ech color resource is a name value pair. resource file saved on res/values folder.
in this example we create a resource file to store color names. this xml resource file name is colors.xml and its located at res/values/colors.xml. we saved our preferred colors name and value in the xml file to use them on app widgets.
finally. we can define TextView background color from xml resource file by android:background attribute as android:background=»@color/AliceBlue». the specified TextView will display AliceBlue background on app.
Set TextView background color programmatically
Источник
Relative Layout Background Color And Image Example In Android Studio
Here we show how to change background color and image in Relative Layout with example in Android Studio.
In this example we create a custom layout in which we display two RelativeLayout’s , one is the parent layout and other one is the child layout in which we display two TextView’s. In the background of Parent Relative Layout we set green color and in the background of child RelativeLayout we set a image/drawable. Finally we get the reference of TextView’s in our Activity and then perform setOnClickListener event on TextView’s. Whenever a user click on any TextView the text value is displayed on screen by using a Toast.
Important Note: We can set color or image in the background of RelativeLayout in XML using background attribute or programmatically means in java class using setBackgroundColor() for color and setBackground() method for setting image.
Step 1: Create a new project and name it RelativeLayout’sBackgroundColorAndImage.
Step 2: Open res -> layout ->activity_main.xml (or) main.xml and add following code:
In this step we open xml file and then create a custom layout in which we display two RelativeLayout’s , one is the parent layout and other one is the child layout in which we display two TextView’s. In the background of Parent Relative Layout we set green color and in the background of child RelativeLayout we set an image/drawable.
Step 3: Open src -> package -> MainActivity.java
In this step Firstly we get the reference of TextView’s and then perform setOnClickListener event on TextView’s so Whenever a user click on any TextView the text value is displayed on screen by using a Toast.
Step 4: Open res -> values-> colors.xml
In this step we define the colors (green and white) that used in the background and text color of TextView’s.
Output:
Now run the app and you will see the below output
Источник
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 и вставьте текст.
Источник
Android TextView Decoration Tutorial
TextViews are the first things that we learn when we start learning Android and due to this whenever we create an Empty Activity, then by default we will see one TextView on the screen with “Hello World!”. So, Hello World! Hope you are learning well. In this blog, we will learn TextView decoration in Android. This blog is going to be an interesting blog as we all use TextViews in our Android application to display some textual information. In this blog, we will learn how to decorate these TextViews in Android. In the beginning, we will learn some of the basic attributes of TextView and after that, we will be having some cool TextViews in our app. So, let’s get started.
TextView
A TextView is a user interface element that is used to display some text or some textual information in our application. Following is an XML code for using TextView in our application:
By using the TextView tag in your application, you can insert a TextView to display the desired text by using android:text property. To decorate a TextView, there are various attributes that can be used. Let’s discuss one by one.
Typeface
By default, Android gives you four fonts that you can use in your application. They are:
You can use these fonts in your TextView by using the android:typeface attribute.
Textstyle
You can emphasize a text by using the android:textStyle attribute. Following are the three options that are available with android:textStyle :
Text size and Text Color
You can change the text size by using the android:textSize attribute and the color of the text can be change by using android:textColor attribute.
Font family
You can change the font family of a TextView by using the android:fontFamily attribute. By default, we have 14 font families that can be used in TextView. Some of these are serif, monospace, casual, cursive, sans-serif, sans-monospace, etc.
ImageIf you want to use your custom font then you can read our blog at MindOrks Blogs.
Text alignment
You can align your text with the help of android:textAlignment attribute. This attribute provides us a lot of options like center align, textStart, textEnd, viewStart, viewEnd, etc.
Text shadow
You can put shadow to your text and change the color of the shadow by using the android:shadowColor attribute. Also, you can use shadowDx and shadowDy to specify the offset of the shadow. For example, a -Dx draws a shadow on the left of the text and +Dx draws a shadow on the right of the text. shadowRadius can be used to specify how much the shadow should be blurred at the edges.
Non Breaking Sentence
You can put a sentence in more than one line. This is possible when the width of the TextView is not enough to hold the contents of the TextView i.e. you are having more texts but the space is not provided.
Gradient
To set the color of the TextView, you can also use Gradient color by using the LinearGradient.
Also, add the below code in you MainActivity.kt file to use LinearGradient:
The parameters of the LinearGradient are:
- x0: x-coordinate for start of gradient line. It is of type float.
- y0: y-coordinate for start of gradient line. It is of type float.
- x1: x-coordinate for end of gradient line. It is of type float.
- y1: y-coordinate for end of gradient line. It is of type float.
- colors: The RGB color to be distributed along the gradient line. It is of type float.
- positions: It is the relative position of each corresponding color in the colors array. It is of type float.
- tile: It is the shader tiling mode. It is of type float.
Clickable span
While reading a text, you can go to somewhere else by clicking on the text. This is the same way as used in websites, where we use hyperlinks to open new page from the existing one. Add the below code in your XML file:
Here, textColorLink is the color of the clickable link and the textColorHighlight is the color used when you click the link.Add the below code in your MainActivity.kt file:
Background Image
You can use some background image in TextView i.e. it seems like the text is written on the image. Add the below code in your XML file:
After that, add the below code in your MainActivity.kt file:
Conclusion
In this blog, we learned how we can decorate TextViews in our application. We learned many ways of decorating the text used in our application. Hope you enjoyed this blog and will implement the learnings of this blog in your application.
Источник