Android phone number input

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

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

Читайте также:  Как удаленно включить android

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

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

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

Источник

Android phone number input

A small library that bring a more powerful widget for telephone number inputs

What can this lib do

The main purpose of this library is to pre-validate, phone numbers when asked to the user. The widget automaticaly genrate a number in the international format. It also bring a more intuitive interface for users. Everytime I personnaly have to enter my phone number, I always ask myself : «Which format should I use ? The international one with the dialing code ? The nationnal one ? Should I remove the fist digit of the number ?»

These kind of question disappear with this widget.

Thanks to the more low level google’s phonenumber library (https://github.com/googlei18n/libphonenumber) it is possible to format phonenumber as needed and also to validate them and now this library act as an interface for this library ! Cool isn’t it ?

This library is made for android from API 15 to API 29 (and probably more in the future ). Installation within android Studio is pretty easy, just add these lines to your gradle dependencies.

  1. Add this in your root build.gradle at the end of repositories:

The widget can be used in your .xml layout, here is an example :

and then in your activity :

There are some useful method such as :

  • setConfig : this method take a CountryConfigurator as parameter
  • getConfig : this method give you back the current configuration applied to the widget
  • getFormatedNumber : this method should be called when the OnValidEntryListener is triggered. The method also accept as the output type as parameter. The default one is INTERNATIONAL but here are the format supported by google’s number formating lib:
    • E164
    • INTERNATIONAL
    • NATIONAL
    • RFC3966
  • setCountry : this method sets the country on the spinner
  • setDisplayMobileHint : this method sets the phone number type that will be displayed as hint
  • setPhoneNumber : this method sets the number and the country.
  • getCountryList : this method returns the list of availale country

There are also some Listener to listen to allowing you to get information from the widget in real time such as:

  • OnCountryChangedListener : triggered when the user decide to change the country in the spinner, you can get the associated country code.
  • OnValidEntryListener : triggered when the user enter a valid number ( may be false )

Three words about the CountryConfigurator

For now it only permit you to display or not some element in the Spiner, such as the flag (1), the country code (2), and the dial code (3). By default all values are set to true, so every thing is displayed

Settings can be aplied by using : phoneView.setConfig(config);

Any suggestions are welcome. This library may not be complete (some flags or country may be missing from the list). Feel free to fork this depos and add new features to this lib. If you have any questions, feel free to ask, I will be happy to answer them.

Читайте также:  Как почистить дамп памяти андроид

About

A small library that bring a more powerful widget for telephone number inputs

Источник

Android phone number input

android-phone-field is A small UI library that allows you to create phone fields with corresponding country flags, and validate the phone number using libphonenumber from google.

The library has two different fields:

  • PhoneEditText : includes EditText alongside the flags spinner
  • PhoneInputLayout : includes a TextInputLayout from the design support library alongside the flags spinner
  • Displays the correct country flag if the user enters a valid international phone number
  • Allows the user to choose the country manually and only enter a national phone number
  • Allows you to choose a default country, which the field will change to automatically if the user chose a different country then cleared the field.
  • Validates the phone number
  • Returns the valid phone number including the country code

In your module’s gradle file add the following dependency, please make sure that you have jcenter in your repositories list

In your layout you can use the PhoneInputLayout

or the PhoneEditText

Then in your Activity/Fragment

In case the default style doesn’t match your app styles, you can extend the PhoneInputLayout, or PhoneEditText and provide your own xml, but keep in mind that you have to provide a valid xml file with at least an EditText (tag = com_lamudi_phonefield_edittext) and Spinner (tag = com_lamudi_phonefield_flag_spinner), otherwise the library will throw an IllegalStateException.

You can also create your own custom view by extending the PhoneField directly.

For better performance and to avoid using json data and then parse it to be used in the library, a simple nodejs is used to convert the countries.json file in raw/countries-generator/ into a plain java utility class that has static list of countries.

The generation script works as follows:

This is probably not the the first library with the same purpose, for instance before I started working on the library I came across IntlPhoneInput which provides almost most of the functionality this library provides, however I chose to develop a new library for the following reasons:

  • This library provides two implementations of PhoneField using EditText and TextInputLayout
  • This library allows users to extend the functionality and use custom layouts if needed to match the application theme
  • This library uses a static list of countries generated from the countries.json file in the raw resources
  1. Inspired by intl-tel-input for jQuery and IntlPhoneInput
  2. Flag images from GoSquared
  3. Original country data from mledoze’s World countries in JSON, CSV and XML which is then used to generate a plain Java file
  4. Formatting/validation using libphonenumber

About

A small library that allows you to create phone fields with corresponding country flags, and validate the phone number using libphonenumber from google.

Источник

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