Android studio поиск по textview kotlin

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 и запустим пример. Сам текст будет выглядеть как ссылка, но реагировать не будет. Чтобы исправить данную проблему, добавим код:

Читайте также:  Java web start android

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

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

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

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

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

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

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

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

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

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

Источник

findViewById in Kotlin

Or how and why we have two ways to avoid it

In Android, if you want to change the properties of views from your layout, like changing the text of a TextView or adding an onClickListener , you would have to first assign that view’s id to a variable by calling findViewById . For example, if you only had one TextView with an id of textView, you’d need to write the following Kotlin code:

As you can imagine, this gets pretty verbose for a large number of views. With Kotlin, we have two separate ways to avoid declaring variables and writing findViewById code:

  1. Kotlin Android Extensions (JetBrains’ approach)
  2. Data Binding (Google’s approach)

Now let’s look at how you use each of the new approaches:

1. Kotlin Android Extensions

To solve the issue of writing useless code, JetBrains has created the Kotlin Android Extensions which have a number of features, but exist primarily to avoid the need for findViewById code. Using them is straightforward, you simply need to import kotlinx.android.synthetic.main.activity_main.* and then you simply reference views by their id from the layout file, for example:

This is super useful, because it makes all of the code we wrote initially unnecessary. The way it works is basically it calls findViewById itself and it creates a cache of views it references any time you want to access that view again.

However, there are a number of issues with this, primarily that it’s Kotlin-only and that it still runs the expensive findViewById operations. For a more in-depth look at the downsides, have a look at this excellent article:

The Argument Over Kotlin Synthetics

It all started with a commit message

As a result, Google recommends not using them, and instead using:

2. Data Binding

To solve the same issue, as well as add some extra functionality (for example observing data changes), Google has created the Data Binding Library. Using this is a bit more involved than Kotlin Android Extensions, but in theory it allows for more complex manipulation of the data and, most importantly, it avoids findViewById calls entirely by creating an object that already contains references to all the views that have ids.

To use it, you first need to enable data binding in your app’s build.gradle

Then, you need to wrap each layout xml file with a tag.

Finally, need to create a variable to reference the object holding all the view ids:

After that, we can access all views using their ids like so:

Both approaches offer multiple benefits and expanded functionality so I encourage digging deeper into them if you’re curious, I just wanted to show you how each is used strictly in the context of avoiding writing boilerplate code. If you have any questions you’re welcome to ask them in the comments section below.

Thanks for reading this article. You can connect with me on LinkedIn.

I’m currently looking for a job in the Geneva area , Switzerland, so please contact me if you know someone in need of a Mobile Developer with Java/Kotlin (Android) and JavaScript (React Native Android/iOS) experience.

If you liked this article, please hit the clap icon 👏 to show your support.

Источник

Я не могу получить доступ к textView в Котлине

Я только новичок в разработке Android и Kotlin. Я написал несколько простых кодов, но это не помогло. Вы можете мне с этим помочь?

Читайте также:  Чаты знакомств для андроида

Я написал это, но не смог получить доступ к textView. Примечание. Мой идентификатор textView тоже textView.

2 ответа

Сначала вам нужно установить id для TextView в вашем XML файле

Тогда в вашей функции onCreate в вашем Activity или Fragment вы получите TextView в своем XML и назначите его Object следующим образом и установите текст после этого

Для решения Kotlin Extensions сделайте следующее

1- перейдите в файл Gradle вашего приложения и добавьте этот плагин

2- и теперь, когда вы напишете это

Он покажет вам textView подчеркнутым красным и говорит, что может импортировать его, как только вы это сделаете, он будет работать. это обойдет findViewById, и он вам больше не понадобится.

Файл build.gradle уровня модуля.

Использование Например, для файла макета с именем result_profile.xml:

Чтобы настроить экземпляр класса привязки для использования с действием, выполните следующие действия в методе onCreate () действия:

Вызовите статический метод inflate (), включенный в сгенерированный класс привязки. Это создает экземпляр класса привязки для использования действием. Получите ссылку на корневое представление, вызвав метод getRoot () или используя синтаксис свойств Kotlin. Передайте корневое представление в setContentView (), чтобы сделать его активным представлением на экране.

Источник

Android TextView Using Kotlin – A Comprehensive Tutorial

Android Tutorial

Kotlin is the official programming language for Android apps development. In this tutorial, we’ll be discussing TextViews in Android applications using Kotlin programming. We’ll create and change TextViews code in Kotlin programming.

Android TextView Overview

Android TextView is a subclass of the View class. The View class typically occupy our window. TextView is used to display text on the screen. We can do a lot of fancy things using TextView.

Let’s start with a fresh project in Android Studio.

Create a new project and make sure you’ve enabled Kotlin in the setup wizard.

Creating TextView in XML Layout

TextView is created in an xml layout in the following manner.

The four attributes defined above are the core attributes of the TextView widget.

  1. The id property is used to set a unique identifier. It’s set as @+id/ followed by the name you assign. The same name would be used to retrieve the TextView property in our Kotlin Activity class.
  2. The text property is used to set the string text to be displayed in the TextView.
  3. As it is evident from the names itself, layout_width and layout_height are used to set the boundaries of the TextView. The wrap_content means wrapping the width, height to the length of the text. The match_parent means the TextView matches the width/height of the enclosed parent view. We can also set hardcoded values in dp (device independent pixels).

Clean Code Tips: Instead of hardcoding the string, define it inside the strings.xml and set the text in the layout as follows.

Let’s apply some attributes over the TextView in XML.

TextView XML Attributes

Let’s give you a quick tour of some of the popular attributes of TextView widget.

  • android:textSize : sets the size of the TextView. It’s recommended to use sp instead of dp. The sp stands for scale independent pixels and scales the font. Example: 16sp.
  • The android:textColor is used to set a color for the text. Typically it is of the format #rgb, #rrggbb, #aarrggbb.
  • The android:background attribute is used to set the background color of the TextView.
  • The android:textStyle is used to set the style among bold, italic, and normal. If you want to set bold and italic, use android:textStyle = “bold|italic”.
  • The android:textAppearance attribute is used to set the style on a TextView, which includes its own color, font, and size. We can create custom styles in the styles.xml file.
  • android:visibility is used to set the visibililty of the text, possible values are visible , invisible , and gone . The gone makes the textview invisible and removes it from the current position in the layout.
  • The android:ellipsize is used to handle situations when the length of the text exceeds the limit.

.

  • android:drawableLeft is used to set a drawable/mipmap image or vector asset besides the TextView.
  • The android:gravity is used to set the position of the text relative to its dimensions.
  • android:layout_margin is used to set the spacing of the TextView from the other views present in the layout. The layout_marginLeft, layout_marginRight, layout_marginTop, layout_marginBottom are used for setting margins on the individiual sides.
  • The android:padding is used to add spacing inside the four sides of the TextView. The possible values are paddingLeft, paddingRight, paddingTop, and paddingBottom.
  • Let’s use the xml attributes on a TextView in our layout.

    Читайте также:  360 total security для android

    Note: We’ve replaced the ConstraintLayout with a LinearLayout to make things easier.

    Notice the opacity in the last TextView

    For more info on XML attributes for Android TextView, visit the Google docs attached at the end of this page or JournalDev Android TextView tutorial.

    In the following section, we’ll create TextView programmatically using Kotlin and set Kotlin functions, properties, and use lambda functions over the TextView.

    Creating Android TextView using Kotlin

    We can get the TextView in our MainActivity.kt Kotlin class using findViewById .

    The findViewById is used to get a view from the XML in the Activity class using the id specified. It works like a dictionary – key/value pair.

    Code Explanation:

    • MainActivity Kotlin class extends AppCompatActivity.
    • We’ve created the textView property by using findViewById . Though from Android API > 24 you can ignore specifying the type explicitly.
    • The text property is used as getter/setter on the TextView. It returns a CharSequence.
    • $ implcitily converts the CharSequence to a String.
    • The text property in Kotlin is equivalent to getText() and setText(String) in Java.
    • To set the string from the strings.xml file, we call resources.getString(R.string. ) . The resources property is equivalent to getResources() from Java.

    Handling Null Values in TextView Kotlin Code

    Kotlin has a very safe way to deal with null values. Optional Types act as a wrapper over the current type. They need to be safely unwrapped to use non-null values, thus enabling null safety in our Kotlin code.

    Let’s look at how the above app behaves when the textView is null.

    So when the text is null, the compiler ignores it.

    When the textView is null, we need to add a safe call to unwrap the textView. This way Kotlin automatically gives us null safety.

    What if the textView is null at runtime?

    It will throw error message as IllegalStateException. TextView cannot be null. .

    So let’s set the TextView properties as Optional in the declaration.

    We’ve set otherTextView to the type TextView .

    So calling anything over the TextView would require a safe call.

    What if the text is null? What do we display instead?

    We use the elvis operator ?: from Kotlin for null safety.

    In the above code, NA gets displayed if otherTextView?.text is null.

    The safe call can be replaced by a let lambda expression too.

    Kotlin Android Extensions

    Thanks to apply plugin: ‘kotlin-android-extensions’ in our build.gradle file, we can directly bind views from the layout in our Kotlin activity class.

    Add the following import statement in your MainActivity.kt class.

    Now you can use the TextView properties directly without using findViewById.

    Android TextView Kotlin onClick Listener

    In the above code, for the setOnClickListener we use lambda expressions from Kotlin. It makes the code shorter and easier to read than Java.

    To make the textViewEllipsize slide, set it to MARQUEE. To make it loop continuously, we’ve set marqueeRepeatLimit to -1.

    The mipMapDrawable is of the type Drawable and setCompoundDrawablesWithIntrinsicBounds() is the equivalent of android:drawablePadding .

    The app output is shown in the following GIF.

    Android TextView extension functions

    We can create Kotlin extension functions on a TextView to add our custom functions and properties.

    The below extension function creates a consistent property for currentTextColor property and setTextColor() function.

    Add the following code outside the class.

    We can then set the color on our TextView using the textColor property.

    Android TextView “with” expression

    Instead of using redundant lines where we set the attributes on the same TextView property like this:

    We can make it better using the with expression.

    Creating a TextView Programmatically in Kotlin

    Below, we’ve created two TextViews programmatically. We’ve set a custom font from the assets folder and set underline on one of the TextViews. Also, we’ve set the string in the form of HTML.

    The assets directory is created under src | main folder and is used to hold the TTF files for the custom fonts.

    Kotlin properties are required to be initialized there itself. If it’s not possible, we can set a lateinit modifier to the property.

    By default, when the textView is created programmatically, its width is match_parent and height is wrap_content .

    The paintFlags is used to add an underline to the string.

    The output with the above TextViews added into the layout programmatically is shown in the following image.

    Using Spannable Strings

    Spannable Strings are useful when we have to set different styles on different substrings of the TextView.

    This brings an end to the comprehensive tutorial on Android TextViews using Kotlin programming.

    Источник

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