- EditText
- Plain Text
- Person Name
- Password и Password (Numeric)
- Phone
- Postal Address
- Multiline Text
- Time и Date
- Number, Number (Signed), Number (Decimal)
- Текст-подсказка
- Вызов нужной клавиатуры
- Интерфейс InputType
- Атрибут android:imeOptions — параметры для текущего метода ввода
- Заблокировать текстовое поле
- Другие свойства
- Методы
- Выделение текста
- Обработка нажатий клавиш
- Пустой ли EditText
- Превращаем EditText в TextView
- Дополнительное чтение
- Android studio edittext setselection
- EditText Code:
- Attributes of EditText:
- Example I – EditText in Android Studio
- Example II – EditText in Android Studio
- TextInputLayout / Floating Labels In EditText:
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 используется атрибут 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" каждый первый символ каждого слова при вводе текста автоматически будет преобразовываться в прописную. Удобно, не так ли?
Значение 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.
Другие свойства
Методы
Основной метод класса EditText — getText(), который возвращает текст, содержащийся в текстовом поле. Возвращаемое значение имеет специальный тип 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
Источник
Android studio edittext setselection
In Android, EditText is a standard entry widget in android apps. It is an overlay over TextView that configures itself to be editable. EditText is a subclass of TextView with text editing operations. We often use EditText in our applications in order to provide an input or text field, especially in forms. The most simple example of EditText is Login or Sign-in form.
Text Fields in Android Studio are basically EditText:
Important Note: An EditText is simply a thin extension of a TextView. An EditText inherits all the properties of a TextView.
Table Of Contents
EditText Code:
We can create a EditText instance by declaring it inside a layout(XML file) or by instantiating it programmatically (i.e. in Java Class).
EditText code in XML:
Retrieving / Getting the Value From EditText In Java Class:
Below is the example code of EditText in which we retrieve the value from a EditText in Java class. We have used this code in the example you will find at the end of this post.
Attributes of EditText:
Now let’s we discuss few attributes that helps us to configure a EditText in your xml.
1. id: id is an attribute used to uniquely identify a text EditText. Below is the example code in which we set the id of a edit text.
2. gravity: The gravity attribute is an optional attribute which is used to control the alignment of the text like left, right, center, top, bottom, center_vertical, center_horizontal etc.
Below is the example code with explanation included in which we set the right gravity for text of a EditText.
3. text: text attribute is used to set the text in a EditText. We can set the text in xml as well as in the java class.
Below is the example code in which we set the text “Username” in a edit text.
Setting text in EditText In Java class:
Below is the example code in which we set the text in a text view programmatically means in java class.
4. hint: hint is an attribute used to set the hint i.e. what you want user to enter in this edit text. Whenever user start to type in edit text the hint will automatically disappear.
Below is the example code with explanation in which we set the hint of a edit text.
Setting hint in EditText In Java class:
Below is the example code in which we set the text in a text view programmatically means in java class.
5. textColor: textColor attribute is used to set the text color of a text edit text. Color value is in the form of “#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”.
Below is the example code with explanation included in which we set the red color for the displayed text of a edit text.
Setting textColor in EditText In Java class:
Below is the example code in which we set the text color of a edit text programmatically means in java class.
6. textColorHint: textColorHint is an attribute used to set the color of displayed hint.
Below is the example code with explanation included in which we set the green color for displayed hint of a edit text.
Setting textColorHint in EditText In Java class:
Below is the example code in which we set the hint color of a edit text programmatically means in java class.
7. textSize: textSize attribute is used to set the size of text of a edit text. We can set the text size in sp(scale independent pixel) or dp(density pixel).
Below is the example code in which we set the 25sp size for the text of a edit text.
Setting textSize in EditText in Java class:
Below is the example code in which we set the text size of a edit text programmatically means in java class.
8. textStyle: textStyle attribute is used to set the text style of a edit text. The possible text styles are bold, italic and normal. If we need to use two or more styles for a edit text then “|” operator is used for that.
Below is the example code with explanation included, in which we set the bold and italic text styles for text.
9. background: background attribute is used to set the background of a edit text. We can set a color or a drawable in the background of a edit text.
Below is the example code with explanation included in which we set the black color for the background, white color for the displayed hint and set 10dp padding from all the side’s for edit text.
Setting Background in EditText In Java class:
Below is the example code in which we set the background color of a edit text programmatically means in java class.
10. padding: padding attribute is used to set the padding from left, right, top or bottom. In above example code of background we also set the 10dp padding from all the side’s of edit text.
Example I – EditText in Android Studio
Below is the example of edit text in which we get the value from multiple edittexts and on button click event the Toast will show the data defined in Edittext.
Step 1: Create a new project in Android Studio and name it EditTextExample.
Step 2: Now Open res -> layout -> xml (or) activity_main.xml and add following code. In this code we have added multiple edittext and a button with onclick functionality.
Step 3: Now open app -> java -> package -> MainActivity.java and add the below code.
In this we just fetch the text from the edittext, further with the button click event a toast will show the text fetched before.
Output:
Now start the AVD in Emulator and run the App. You will see screen asking you to fill the data in required fields like name, password(numeric), email, date, contact number. Enter data and click on button. You will see the data entered will be displayed as Toast on screen.
Example II – EditText in Android Studio
Below is the example of edit text in which we get the value from a edit text on button click event and then display it in a Toast. Below is the final output and code.
Step 1: Create a new project in Android Studio and name it EditTextExample.
Step 2: Now Open res -> layout -> xml (or) activity_main.xml and add following code. Here we will design one EditText for filling name and one Button which will be used to display the name entered by the user.
Step 3: Now open app -> java -> package -> MainActivity.java and add the below code. The explanation is included in the code itself as comment.
Output:
Now start the AVD in Emulator and run the App. You will see screen asking you to fill your name. Enter your name and click on button. You will see the name entered will be displayed as Toast on screen.
TextInputLayout / Floating Labels In EditText:
TextInputLayout is a new element introduced in Material Design Support library to display the floating label in EditText. Read our advance Floating Labels tutorial to learn how to use it in your App.
Источник