- 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
- Дополнительное чтение
- Working with the EditText
- Get Value from the EditText and Set value to the TextView
- Complete Code for MainActivity.java
- Add Validation if you want
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
Источник
Working with the EditText
The EditText is the standard text entry widget in Android apps. If the user needs to enter text into an app, this is the primary way for them to do that.
There are many important properties that can be set to customize the behavior of an EditText . Several of these are listed below. Check out the official text fields guide for even more input field details.
An EditText is added to a layout with all default behaviors with the following XML:
Note that an EditText is simply a thin extension of the TextView and inherits all of the same properties.
Getting the value of the text entered into an EditText is as follows:
By default, any text contents within an EditText control is displayed as plain text. By setting inputType , we can facilitate input of different types of information, like phone numbers and passwords:
Most common input types include:
Type | Description |
---|---|
textUri | Text that will be used as a URI |
textEmailAddress | Text that will be used as an e-mail address |
textPersonName | Text that is the name of a person |
textPassword | Text that is a password that should be obscured |
textVisiblePassword | Text, next button, and no microphone input |
number | A numeric only field |
phone | For entering a phone number |
date | For entering a date |
time | For entering a time |
textMultiLine | Allow multiple lines of text in the field |
You can set multiple inputType attributes if needed (separated by ‘|’)
We might want to limit the entry to a single-line of text (avoid newlines):
You can limit the characters that can be entered into a field using the digits attribute:
This would restrict the digits entered to just «0» and «1». We might want to limit the total number of characters with:
Using these properties we can define the expected input behavior for text fields.
You can adjust the highlight background color of selected text within an EditText with the android:textColorHighlight property:
with a result such as this:
You may want to set the hint for the EditText control to prompt a user for specific input with:
which results in:
Assuming you are using the AppCompat library, you can override the styles colorControlNormal , colorControlActivated , and colorControlHighlight :
If you do not see these styles applied within a DialogFragment, there is a known bug when using the LayoutInflater passed into the onCreateView() method.
The issue has already been fixed in the AppCompat v23 library. See this guide about how to upgrade. Another temporary workaround is to use the Activity’s layout inflater instead of the one passed into the onCreateView() method:
Check out the basic event listeners cliffnotes for a look at how to listen for changes to an EditText and perform an action when those changes occur.
Traditionally, the EditText hides the hint message (explained above) after the user starts typing. In addition, any validation error messages had to be managed manually by the developer.
Starting with Android M and the design support library, the TextInputLayout can be used to setup a floating label to display hints and error messages. First, wrap the EditText in a TextInputLayout :
Now the hint will automatically begin to float once the EditText takes focus as shown below:
We can also use the TextInputLayout to display error messages using the setError and setErrorEnabled properties in the activity at runtime:
Here we use the addTextChangedListener to watch as the value changes to determine when to display the error message or revert to the hint.
TextInputLayout can expose a character counter for an EditText defined within it. The counter will be rendered below the EditText and can change colors of both the line and character counter if the maximum number of characters has been exceeded:
The TextInputLayout simply needs to define app:counterEnabled and app:CounterMaxLength in the XML attributes. These settings can also be defined dynamically through setCounterEnabled() and setCounterMaxLength() :
If you use an EditText with an input password type, you can also enable an icon that can show or hide the entire text using the passwordToggleEnabled attribute. You can also change the default eye icon with passwordToggleDrawable attribute or the color hint using the passwordToggleTint attribute. See the TextInputLayout attributes for more details.
Make sure you have the app namespace ( xmlns:app=»http://schemas.android.com/apk/res-auto» defined in your outer layout. You can type appNS as a shortcut in Android Studio to be declared.
The hint text can be styled by defining app:hintTextAppearance , and the error text can be changed with app:errorTextAppearance. The counter text and overflow text can also have their own text styles by defining app:counterTextAppearance and app:counterOverflowTextAppearance . We can use textColor , textSize , and fontFamily to help change the color, size, or font (place inside styles.xml):
Check out the official text fields guide for a step-by-step on how to setup autocomplete for the entry.
Источник
Get Value from the EditText and Set value to the TextView
Any android app has two parts in it – frontend and backend. Frontend refers to the visualization of the components i.e. how your app will look and appear to the other users. Backend part refers to the logic behind the functioning of your app.
Whenever we click on any button or submit any form, the backend code decides what action to perform next or what to do with the data received from user etc.
In our previous tutorials, we have seen how different types of layout are useful for for GUI designing which is the frontend part. Here in this tutorial, we are going to focus and code for the backend part.
In our example, we will take input from the user through EditText view and will display it in the TextView . Additionally, we will also get to see a buttonClickListener that is used to define the action to be performed when a button is clicked in the app.
Below is th design that we will be working on.
In the MainActivity.java file, we will define global variables as follows:
After setting the main layout using the setContentView() method in the onCreate() method, attach the global variables that we defined to the GUI views using findViewById() method as shown below.
As the name of the method suggests, findViewById() returns an instance for the view defined in layout XML. In other words, this method is used to get the view instance in Java, that you have made and used in layout XML. This is done by mentioning the id of the view that you have defined in XML. The view created in XML is used in Java to manipulate it dynamically.
Note: findViewById() method returns only View , but it does not tell which view is returned i.e. whether the view is Button, TextView, EditText, etc. Therefore, you need to typecast the view returned by this method.
Now, to enable button click event, we need to attach a click listener to our button instance. It is done by writing the following code:
Once you add this code, whenever th submit button is clicked, the method onClick will be called and the code inside it will be executed.
According to your requirements, we want to get the text that user will enter in the EditText and show it in the TextView whenever the submit button is clicked. Therefore, let’s place the following code inside onClick() method:
We have used getText() method to get the text entered in the EditText views. But getText() method returns an Editable instance and therefore we have typecasted it to convert it into String for further use. This can be done by using the toString() method.
Note: We defined editName and editPassword as global variables, hence they can be used in any method.
So now that we have user inputted name and password values, we can easily apply any logic on this dataset like performing authentication for login etc. For now, we are just going to display this information in a textView. For that, we will be using the setText() method with our TextView instance to display information in it. This is done using the following code:
Now, whenever the submit button is clicked, onClick() method of submitButton is called and the user input values are stored in the name and password variables using the getText() method on EditText instances. Then, using setText() method, the input values are displayed in the TextView.
Now, when you press the Reset button, the text in the TextView should be reset i.e cleared. For that, we will have to implement click listener on RESET button too. Following is the code to do so:
You just need to set text equal to «» (empty), for both the EditText as well as for TextView. Additionally, to get the typing cursor on the Name EditText field, we can use requestFocus() method with the editName instance.
Complete Code for MainActivity.java
You can download the whole project here
Add Validation if you want
You can also add validation to this like display a message if the user leaves the fields name and password empty and taps on the submit button.
In that case, all we have to do is check if name or password is empty, if found empty, display a message using a Toast saying, both the fields are required.
Источник