Android edittext settext kotlin

EditText

Компонент EditText — это текстовое поле для пользовательского ввода, которое используется, если необходимо редактирование текста. Следует заметить, что EditText является наследником TextView.

В Android Studio на панели инструментов текстовые поля можно найти в категории Texts под разными именами.

Для быстрой разработки текстовые поля снабдили различными свойствами и дали разные имена: Plain Text, Person Name, Password, Password (Numeric), E-mail, Phone, Postal Address, Multiline Text, Time, Date, Number, Number (Signed), NumberDecimal.

Plain Text

Plain Text — самый простой вариант текстового поля без наворотов. При добавлении в разметку его XML-представление будет следующим:

Person Name

При использовании элемента Person Name в XML добавляется атрибут inputType, который отвечает за вид клавиатуры (только буквы) при вводе текста.

Password и Password (Numeric)

При использовании Password в inputType используется значение textPassword. При вводе текста сначала показывается символ, который заменяется на звёздочку. Если используется элемент Password (Numeric), то у атрибута inputType используется значение numberPassword. В этом случае на клавиатуре будут только цифры вместо букв. Вот и вся разница.

E-mail

У элемента E-mail используется атрибут android:inputType=»textEmailAddress». В этом случае на клавиатуре появляется дополнительная клавиша с символом @, который обязательно используется в любом электронном адресе.

Phone

У элемента Phone используется атрибут android:inputType=»phone». Клавиатура похожа на клавиатуру из старого кнопочного сотового телефона с цифрами, а также с кнопками звёздочки и решётки.

Postal Address

Multiline Text

У Multiline Text используется атрибут android:inputType=»textMultiLine» позволяющий сделать текстовое поле многострочным. Дополнительно можете установить свойство Lines (атрибут android:lines), чтобы указать количество видимых строк на экране.

Time и Date

Атрибут android:inputType=»time» или android:inputType=»date». На клавиатуре цифры, точка, запятая, тире.

Number, Number (Signed), Number (Decimal)

Атрибут android:inputType=»number» или numberSigned или numberDecimal. На клавиатуре только цифры и некоторые другие символы.

Текст-подсказка

Веб-мастера знают о таком атрибуте HTML5 как placeholder, когда в текстовом поле выводится строчка-подсказка приглушенным (обычно серым цветом). Живой пример приведён ниже.

Подсказка видна, если текстовый элемент не содержит пользовательского текста. Как только пользователь начинает вводить текст, то подсказка исчезает. Соответственно, если удалить пользовательский текст, то подсказка появляется снова. Это очень удобное решение во многих случаях, когда на экране мало места для элементов.

В Android у многих элементов есть свойство Hint (атрибут hint), который работает аналогичным образом. Установите у данного свойства нужный текст и у вас появится текстовое поле с подсказкой.

Запускаем приложение и видим подсказку, которая исчезает при попытке ввести текст.

Вызов нужной клавиатуры

Не во всех случаях нужна стандартная клавиатура с буковками и цифрами. Если вы пишете калькулятор, то проще показать пользователю цифровую клавиатуру. А если нужно ввести электронный адрес, то удобнее показать клавиатуру, где уже есть символ @. Ну а если ваше приложение пишется для котов, то достаточно вывести только те буквы, из которых можно составить слова Мяу и Жрать давай (к сожалению, такой клавиатуры ещё нет, но Google работает в этом направлении).

У элемента EditText на этот случай есть атрибут inputType:

В данном случае с атрибутом inputType=»textCapWords&quot каждый первый символ каждого слова при вводе текста автоматически будет преобразовываться в прописную. Удобно, не так ли?

Значение textCapSentences делает прописным каждый первый символ предложения.

Если вам нужен режим CapsLock, то используйте значение textCapCharacters и все буквы сразу будут большими при наборе.

Для набора телефонного номера используйте phone, и тогда вам будут доступны только цифры, звёздочка (*), решётка (#).

Для ввода веб-адресов удобно использовать значение textUri. В этом случае у вас появится дополнительная кнопочка .com (при долгом нажатии на нее появятся альтернативные варианты .net, .org и др.).

Вот вам целый список доступных значений (иногда различия очень трудно различимы)

Интерфейс InputType

Кроме использования атрибута android:inputType мы можем добиться нужного поведения от текста при помощи интерфейса InputType.

Атрибут android:imeOptions — параметры для текущего метода ввода

У текстовых полей есть атрибут android:imeOptions, с помощью которого настраиваются параметры для текущего метода ввода. Например, когда EditText получает фокус и отображается виртуальная клавиатура, эта клавиатура содержит кнопку «Next» (Далее), если атрибут android:imeOptions содержит значение actionNext. Если пользователь касается этой кнопки, фокус перемещается к следующему компоненту, который принимает пользовательский ввод. Если компонент EditText получает фокус и на виртуальной клавиатуре появляется кнопка «Done» (Готово), значит использовался атрибут android:imeOptions со значением actionDone. Как только пользователь касается этой кнопки, система скрывает виртуальную клавиатуру.

Заблокировать текстовое поле

Для блокировки текстового поля присвойте значения false свойствам Focusable, Long clickable и Cursor visible.

Другие свойства

Методы

Основной метод класса EditTextgetText(), который возвращает текст, содержащийся в текстовом поле. Возвращаемое значение имеет специальный тип Editable, а не String.

Читайте также:  Не поворачивать экран андроид

Соответственно, для установки текста используется метод setText().

В Kotlin может возникнуть проблема, если программист захочет использовать конструкцию присвоения через свойство.

Большинство методов для работы с текстом унаследованы от базового класса TextView: setTypeface(null, Typeface), setTextSize(int textSize), SetTextColor(int Color).

Выделение текста

У EditText есть специальные методы для выделения текста:

  • selectAll() — выделяет весь текст;
  • setSelection(int start, int stop) — выделяет участок текста с позиции start до позиции stop;
  • setSelection(int index) — перемещает курсор на позицию index;

Предположим, нам нужно выделить популярное слово из трёх букв в большом слове (это слово «кот», а вы что подумали?).

Ещё есть метод setSelectAllOnFocus(), который позволяет выделить весь текст при получении фокуса.

Обработка нажатий клавиш

Для обработки нажатий клавиш необходимо зарегистрировать обработчик View.OnKeyListener, используя метод setOnKeyListener() элемента EditText. Например, для прослушивания события нажатия клавиши Enter во время ввода текста пользователем (или котом), используйте следующий код:

Пустой ли EditText

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

Также можно проверять длину текста, если она равно 0, значит текст пуст.

Превращаем EditText в TextView

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

Также можно установить эти свойства через XML, кроме последнего пункта.

Дополнительное чтение

Beware EditText on API 21 — разница между версиями 21 и 22

Источник

Установка текста в EditText Kotlin

Я пытаюсь установить текст в EditText, но он говорит:

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

Не говорите использовать setText , потому что я использую kotlin, а не Java.

14 ответов

Используйте setText(String) , поскольку editText.text ожидает Editable , а не String .

Используйте setText(String) , поскольку editText.text ожидает Editable , а не String . пример: — editText.setText(String)

Или используйте это editText.text = Editable.Factory.getInstance().newEditable(String)

У меня была та же проблема в моих проектах, я привожу вам пример, который показывает, как получать и задавать данные в макетах с помощью Kotlin: есть одна кнопка save_button и два поля для редактирования текста edit_name и edit_password .

Или приведите к TextView , но я считаю, что это должно быть исправлено на стороне kotlin для удобства разработчиков!

Или с некоторыми расширениями:

Ты можешь написать:

Но, к сожалению, вы просто не можете написать просто someEditText.text = «someTextValue»

Посмотрите на API EditText:

void setText (CharSequence text, TextView.BufferType type)

Или вы можете использовать свойство extension:

И используйте .value= вместо .text=

Если вы хотите использовать getter .text из принципа, используйте:

Простое решение

Просто используйте edittext.setText(yourdata ) вместо edittext.text , поскольку EditText доступен для редактирования, edittext.text используется для TextView

Например:

Вот и все его работа для меня.

Использование setText(String) , поскольку EditText.text требует editable , а не String

ПОЧЕМУ?

Хорошее объяснение Майкла в разделе эта ссылка. Посетите эту ссылку для более подробной информации

При генерации синтетического свойства для пары «геттер / установщик» Java Kotlin сначала ищет геттер. Получателя достаточно, чтобы создать синтетическое свойство с типом получателя. С другой стороны, свойство не будет создано, если присутствует только установщик.

Когда сеттер входит в игру, создание свойств становится более сложным. Причина в том, что геттер и сеттер могут иметь разные типы. Кроме того, получатель и / или установщик могут быть переопределены в подклассе.

Попробуйте использовать nametxt.post: nametxt.post ()

Используйте как это:

Методы, которые следуют соглашениям Java для методов получения и установки (методы без аргументов с именами, начинающимися с get, и методы с одним аргументом с именами, начинающимися с set), представлены как свойства в Kotlin. Но, генерируя свойство для пары геттер / сеттер Java, Kotlin сначала ищет геттер. Получателя достаточно, чтобы вывести тип свойства из типа получателя. С другой стороны, свойство не будет создано, если присутствует только установщик (потому что Kotlin не поддерживает свойства только для набора в настоящее время).

Когда сеттер вступает в игру, процесс генерации свойств становится немного неоднозначным. Причина в том, что геттер и сеттер могут иметь разные типы. Более того, геттер и / или сеттер могут быть переопределены в подклассе, что в точности относится к EditText в Android.

В вышеприведенном случае класс Android TextView содержит геттер

И сеттер пустоты

Если бы у меня была переменная типа TextView, мой код работал бы нормально. Но я использовал класс EditText, который содержит переопределенный метод получения

Это означает, что вы можете получить Editable для EditText и установить Editable для EditText. Поэтому Kotlin разумно создает синтетический текст свойства типа Editable. Так как класс String не является редактируемым, поэтому я не могу назначить экземпляр String свойству text класса EditText.

Похоже, что JetBrains забыл указать доминирующую роль методов-получателей при создании свойств kotlin для методов-получателей и сеттеров Java. В любом случае, я отправил запрос на загрузку на сайт Jet Brains kotlin через github.

Здесь есть несколько рабочих ответов, но если вы все еще хотите использовать формат свойств и ваш код выглядит чистым, вы можете написать расширение:

Затем вы можете использовать его как таковой:

Источник

Tutorialwing

In this article, we will learn about android EditText using Kotlin With Example. We will learn how to use different attributes of EditText to set id, text, hint text etc.

In this article, we will get answer to questions like –

  • What is EditText?
  • Why should we consider EditText while designing ui for any app?
  • What are possibilities using EditText while designing ui? etc.

Let’s have a quick demo of things we want to cover in this tutorial –

Output

Tutorialwing EditText Using Kotlin

Tutorialwing EditText Using Kotlin

Video Output

Getting Started

We can define android EditText Widget as below –

Android EditText Widget is subclass of TextView and used to take input from user and modify the text.

While defining the EditText using Kotlin, we also mention about the inputType acceptable by this EditText. For example, to take plain text as input, we use android:inputType=”text”. Keyboard type shown also changes based on the value provided in inputType. For example, if you use numberPassword as inputType, Keyboard shown will appear as shown below –

Читайте также:  Как войти гугл аккаунт для андроид если забыл пароль

Android EditText numberPassword input Type

Android EditText numberPassword input Type

Now, how do we use EditText in android application ?

Creating New Project

At first, we will create an application.
So, follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as EditTextUsingKotlin. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access Android EditText Using Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

Now, we can access view in Kotlin file without using findViewById() method.

Using EditText in Kotlin

Follow steps below to use EditText in newly created project –

  • Open res/layout/activity_main.xml file. Then, add below code in it –
  • We can also access it in Kotlin File, MainActivity.kt, as below –

We can access EditText using it’s id in Kotlin file.

Now, run the application. We will get output as below –

Different Attributes of EditText in XML

Now, we will see how to use different attributes of Android EditText using Kotlin to customise it –

Set Id of EditText

Many a time, we need id of View to access it in Kotlin file or create ui relative to that view in xml file. So, we can set id of EditText using android:id attribute like below –

Here, we have set id of EditText as editText using android:id=”” attribute. So, if we need to reference this EditText, we need to use this id – editText.
Learn to Set ID of EditText Dynamically

Set Width of EditText

We use android:layout_width=”” attribute to set width of EditText.
We can do it as below –

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Learn to Set Width of EditText Dynamically

Set Height of EditText

We use android:layout_height=”” attribute to set height of EditText.
We can do it as below –

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Learn to Set Height of EditText Dynamically

Set Padding of EditText

We use android:padding=”” attribute to set padding of EditText.
We can do it as below –

Here, we have set padding of 10dp in EditText using android:padding=”” attribute.
Learn to Set Padding of EditText Dynamically

Set Margin of EditText

We use android:layout_margin=”” attribute to set margin of EditText.
We can do it as below –

Here, we have set margin of 10dp in EditText using android:layout_margin=”” attribute.
Learn to Set Margin of EditText Dynamically

Set Background of EditText

We use android:background=”” attribute to set background of EditText.
We can do it as below –

Here, we have set background of color #ff0000 in EditText using android:background=”” attribute.
Learn to Set Background of EditText Dynamically

Set Visibility of EditText

We use android:visibility=”” attribute to set visibility of EditText.
We can do it as below –

Here, we have set visibility of EditText using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Learn to Set Visibility of EditText Dynamically

Set Text of EditText

We use android:text=”” attribute to set text of EditText.
We can do it as below –

Here, we have set text (“Hello Tutorialwing”) in EditText using android:text=”” attribute.
Similarly, we can set any text using this attribute.
Learn to Set Text of EditText Dynamically

Set Color of Text in EditText

We use android:textColor=”” attribute to set color of text in EditText.
We can do it as below –

Here, we have set color (#ffffff i.e. white) of text (“Hello Tutorialwing”) in EditText using android:textColor=”” attribute. Similarly, we can set any color using this attribute.
Learn to Set Color of EditText Dynamically

Set Gravity of EditText

We use android:gravity=”” attribute to set gravity of text in EditText.
We can do it as below –

Here, we have set gravity of text in EditText using android:gravity=”” attribute. Attribute value can be – “center_horizontal”, “center”, “center_vertical” etc.
Learn to Set Gravity of EditText Dynamically

Set Text in Uppercase, Lowercase

If we need to show text of EditText in uppercase or lowercase etc.

Set text in uppercase

We can use android:textAllCaps=”true” attribute to set text in uppercase. We can do it as below –

Attribute android:textAllCaps=”true” sets text in uppercase. So, HELLO TUTORIALWING is set in EditText.

By default, false is set in this attribute. So, Whatever value is written in android:text=”” attribute, it will be set as it is. For example,

Above code will set Hello Tutorialwing to EditText.

How do we set text in lowercase?

  • In xml file – write all the text in lowercase.
  • In kotlin file – take text as string. Then, convert it in lowercase. Then, set it to EditText.

Set Size of Text in EditText

We use android:textSize=”” attribute to set size of text in EditText.
We can do it as below –

Here, we have set size of text in EditText using android:textSize=”” attribute.
Learn to Set Size of Text of EditText Dynamically

Set Style (Bold/italic) of Text in EditText

We use android:textStyle=”” attribute to set style (bold, italic etc.) of text in EditText.
We can do it as below –

Here, we have set style of text in EditText using android:textStyle=”” attribute. This attribute can take bold, italic or normal.
Learn to Set Style of Text of EditText Dynamically

Set Letter Spacing of Text in EditText

We use android:letterSpacing=”” attribute to set spacing between letters of text in EditText.
We can do it as below –

Here, we have set spacing between letters of text in EditText using android:letterSpacing=”” attribute.
Learn to Set Letter Spacing of Text of EditText Dynamically

Set Typeface of Text in EditText

We use android:typeface=”” attribute to set typeface in EditText.
We can do it as below –

Here, we have set typeface of text in EditText using android:typeface=”” attribute. This attribute can take values – “sans”, “normal”, “monospace” or “normal”.
Learn to Set Typeface of EditText Dynamically

Set fontFamily of Text in EditText

We use android:fontFamily=”” attribute to set fontFamily of text in EditText.
We can do it as below –

Here, we have set fontFamily (Here, sans-serif) of text in EditText using android:fontFamily=”sans-serif” attribute.

Till now, we have see how to use android EditText using Kotlin. We have also gone through different attributes of TextView to perform certain task. Let’s have a look at list of such attributes and it’s related task.

Different Attributes of Android EditText Widget

Below are the various attributes that are used to customise android EditText Widget. However, you can check the complete list of attributes of EditText in it’s official documentation site. Here, we are going to list some of the important attributes of this EditText –

Sr. XML Attributes Description
1 android:background Use to set background to this View.
2 android:backgroundTint Use to set tint to the background of this view.
3 android:clickable Use to set true when you want to make this View clickable. Otherwise, set false.
4 android:drawableBottom Use to set drawable to bottom of the text in this view.
5 android:drawableEnd Use to set drawable to end of the text in this view.
6 android:drawableLeft Use to set drawable to left of the text in this view.
7 android:drawablePadding Use to set padding to drawable of the view.
8 android:drawableRight Use to set drawable to right of the text in this view.
9 android:drawableStart Use to set drawable to start of the text in this view.
10 android:drawableTop Use to set drawable to top of the text in this view.
11 android:elevation Use to set elevation to this view.
12 android:gravity Use to set gravity of the text in this view. For example, center, horizontal_center, vertical_center etc.
13 android:height Use to set height of the EditText.
14 android:hint Use to set hint to be shown when there is no text in the EditText.
15 android:inputMethod It sets, it specifies that editText should use specified input method.
16 android:inputType This is used to define what are the types of data that can be entered by the user for this View. For example, Phone, Password, Number, Date, Time etc.
17 android:lines If you want to set height of the View by number of lines, you can do it using this attribute. For example, android:lines=”2”, it means height of View will be 2 lines.
18 android:maxHeight Use to set maximum height of the View.
19 android:minHeight Use to set minimum height of the View.
20 android:maxLength Use to set maximum character length that can be entered in the View.
21 android:maxLines Use to set maximum lines this View can have.
22 android:minLines Use to set minimum lines this View can have.
23 android:maxWidth Use to set maximum width this View can have.
24 android:minWidth Use to set minimum width this EditText can have.
25 android:numeric If sets, it specifies that EditText has numeric input method.
26 android:password Use this attribute if you want to show the entered text as password dots. For example, If you enter ABCD, it will be shown as ****.
27 android:phoneNumber If set, specifies that this EditText has a phone number input method.
28 android:text Use to set the text of the EditText
29 android:textAllCaps Use this attribute to show the text in capital letters.
30 android:textColor Use to set color of the text.
31 android:textSize Use to set size of the text.
32 android:textStyle Use to set style of the text. For example, bold, italic, bolditalic etc.
33 android:typeface Use to set typeface of the text. For example, normal, sans, serif, monospace.
34 android:width Use to set width of the EditText.

We have seen different attributes of EditText and how to use it. If you wish to visit post to learn more about it

Thus, we have seen what is EditText, how can we use android EditText using Kotlin ? etc. We also went through different attributes of android EditText.

Источник

Читайте также:  Скайп регистрация планшет андроид
Оцените статью