Android studio edittext input type

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

Источник

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.

Источник

Android EditText with Examples

In android, EditText is a user interface control which is used to allow the user to enter or modify the text. While using EditText control in our android applications, we need to specify the type of data the text field can accept using the inputType attribute.

For example, if it accept plain text, then we need to specify the inputType as “text”. In case if EditText field is for password, then we need to specify the inputType as “textPassword”.

In android, EditText control is an extended version of TextView control with additional features and it is used to allow users to enter input values.

In android, we can create EditText control in two ways either in XML layout file or create it in Activity file programmatically.

Create a EditText in Layout File

Following is the sample way to define EditText control in XML layout file in android application.

xml version= «1.0» encoding= «utf-8» ?>
LinearLayout xmlns: android = «http://schemas.android.com/apk/res/android»
android :layout_width= «match_parent»
android :layout_height= «match_parent»
android :orientation= «vertical» >
EditText
android :id= «@+id/txtSub»
android :layout_width= «match_parent»
android :layout_height= «wrap_content»
android :hint= «Subject»
android :inputType= «text»/>
LinearLayout >

If you observe above code snippet, here we defined EditText control to accept plain text by using inpuType as “text” in xml layout file.

Create EditText Control in Activity File

In android, we can create EditText control programmatically in an activity file to allow users to enter text based on our requirements.

Following is the example of creating EditText control dynamically in an activity file.

public class MainActivity extends AppCompatActivity <
@Override
protected void onCreate(Bundle savedInstanceState) <
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
LinearLayout linearLayout = (LinearLayout) findViewById(R.id. linearlayout );
EditText et = new EditText( this );
et.setHint( «Subject» );
linearLayout.addView(et);
>
>

Set the Text of Android EditText

In android, we can set the text of EditText control either while declaring it in Layout file or by using setText() method in Activity file.

Following is the example to set the text of TextView control while declaring it in XML Layout file.

If you observe above example we used android:text property to the set required text for EditText control in XML Layout file.

Following is another way to set the text of EditText control programmatically in activity file using setText() method.

If you observe above code snippet, we are finding the EditText control which we defined in XML layout file using id property and setting the text using setText() method.

Get Text of Android EditText

In android, we can get the text of EditText control by using getText() method in Activity file.

Following is the example to get text of EditText control programmatically in activity file using getText() method.

public class MainActivity extends AppCompatActivity <
@Override
protected void onCreate(Bundle savedInstanceState) <
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
EditText et = (EditText) findViewById(R.id. txtSub );
String name = et.getText().toString();
>
>

If you observe above code snippet, we are finding the EditText control which we defined in XML layout file using id property and getting the text of EditText control using getText() method.

Android EditText Attributes

The following are some of the commonly used attributes related to EditText control in android applications.

Attribute Description
android:id It is used to uniquely identify the control
android:gravity It is used to specify how to align the text like left, right, center, top, etc.
android:text It is used to set the text.
android:hint It is used to display the hint text when text is empty
android:textColor It is used to change the color of the text.
android:textColorHint It is used to change the text color of hint text.
android:textSize It is used to specify the size of the text.
android:textStyle It is used to change the style (bold, italic, bolditalic) of text.
android:background It is used to set the background color for edit text control
android:ems It is used to make the textview be exactly this many ems wide.
android:width It makes the TextView be exactly this many pixels wide.
android:height It makes the TextView be exactly this many pixels tall.
android:maxWidth It is used to make the TextView be at most this many pixels wide.
android:minWidth It is used to make the TextView be at least this many pixels wide.
android:textAllCaps It is used to present the text in all CAPS
android:typeface It is used to specify the Typeface (normal, sans, serif, monospace) for the text.
android:textColorHighlight It is used to change the color of text selection highlight.
android:inputType It is used to specify the type of text being placed in text fields.
android:fontFamily It is used to specify the fontFamily for the text.
android:editable If we set false, EditText won’t allow us to enter or modify the text

Android EditText Control Example

Following is the example of using multiple EditText controls with different input types like password, phone, etc. in LinearLayout to build an android application.

Create a new android application using android studio and give names as EditTextExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

xml version= «1.0» encoding= «utf-8» ?>
LinearLayout xmlns: android = «http://schemas.android.com/apk/res/android»
android :layout_width= «match_parent»
android :layout_height= «match_parent»
android :paddingLeft= «40dp»
android :orientation= «vertical» android :id= «@+id/linearlayout» >
EditText
android :id= «@+id/txtName»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_marginTop= «25dp»
android :ems= «10»
android :hint= «Name»
android :inputType= «text»
android :selectAllOnFocus= «true»/>
EditText
android :id= «@+id/txtPwd»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :ems= «10»
android :hint= «Password 0 to 9»
android :inputType= «numberPassword»/>
EditText
android :id= «@+id/txtEmai»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :ems= «10»
android :hint= «Email»
android :inputType= «textEmailAddress»/>
EditText
android :id= «@+id/txtDate»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_below= «@+id/editText3»
android :ems= «10»
android :hint= «Date»
android :inputType= «date»/>
EditText
android :id= «@+id/txtPhone»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :ems= «10»
android :hint= «Phone Number»
android :inputType= «phone»
android :textColorHint= «#FE8DAB»/>
Button
android :id= «@+id/btnSend»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :text= «submit»
android :textSize= «16sp»
android :textStyle= «normal|bold»/>
TextView
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :id= «@+id/resultView»
android :layout_marginTop= «25dp»
android :textSize= «15dp»/>
LinearLayout >

If you observe above code we created multiple EditText controls with different inputTypes, such as password, email address, date, phone number, plain text.

Once we are done with the creation of layout with required controls, we need to load the XML layout resource from our activity onCreate() callback method, for that open main activity file MainActivity.java from \java\com.tutlane.edittextexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.edittextexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity <
Button btnSubmit ;
EditText name , password , email , dob , phoneno ;
TextView result ;
@Override
protected void onCreate(Bundle savedInstanceState) <
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
name =(EditText)findViewById(R.id. txtName );
password = (EditText)findViewById(R.id. txtPwd );
email = (EditText)findViewById(R.id. txtEmai );
dob = (EditText)findViewById(R.id. txtDate );
phoneno = (EditText)findViewById(R.id. txtPhone );
btnSubmit = (Button)findViewById(R.id. btnSend );
result = (TextView)findViewById(R.id. resultView );
btnSubmit .setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
if ( name .getText().toString().isEmpty() || password .getText().toString().isEmpty() || email .getText().toString().isEmpty() || dob .getText().toString().isEmpty()
|| phoneno .getText().toString().isEmpty()) <
result .setText( «Please Fill All the Details» );
> else <
result .setText( «Name — » + name .getText().toString() + » \n » + «Password — » + password .getText().toString()
+ » \n » + «E-Mail — » + email .getText().toString() + » \n » + «DOB — » + dob .getText().toString()
+ » \n » + «Contact — » + phoneno .getText().toString());
>
>
>);
>
>

If you observe above code we are calling our layout using setContentView method in the form of R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used file name activity_main and we are getting the text of our EditText controls whenever we click on button.

Generally, during the launch of our activity, the onCreate() callback method will be called by the android framework to get the required layout for an activity.

Output of Android EditText Example

When we run the above example using the android virtual device (AVD) we will get a result like as shown below.

If you observe the above result, the system displaying an appropriate on-screen keyboard for each EditText control based on the defined inputType attribute and displayed a message if we click on the button without entering details in fields.

Once we enter details in all fields and click on Button we will get a result like as shown below.

This is how we can use EditText control in android applications to allow the user to enter or modify the text based on our requirements.

Источник

Читайте также:  Компьютер планшет андроид это
Оцените статью