Android studio textinputlayout style

TextInputLayout

Макет TextInputLayout сначала появился в библиотеке Android Design Support Library и добавляет немного красоты к текстовому полю. Когда пользователь начинает вводить текст в текстовом поле, то подсказка, заданная в этом компоненте, всплывает над ним в специальном TextView. Пример можно увидеть на видео.

Библиотека больше не развивается, поэтому используйте AndroidX, которую я и буду теперь использовать в описании.

Компонент можно найти на панели инструментов в разделе Text.

При добавлении компонента через визуальный редактор автоматически добавляется дочерний элемент TextInputEditText.

Так выглядел компонент в составе Support Library.

Подсказку не обязательно указывать в атрибуте android:hint у текстового поля. Можно программно присвоить через метод:

Стилизация

В AndroidX у компонента появились новые стили: OutlinedBox, FilledBox. Можете самостоятельно запустить пример с двумя стилями и посмотреть на отличия.

Далее идёт текст для старой версии статьи. Вам следует самостоятельно обновить нужные фрагменты кода.

Общая стилизация доступна следующим образом. Пропишем стили в styles.xml:

Обработка ошибки

Предыдущий пример показывал применение подсказки. Но также можно выводить сообщения об ошибке. Здесь потребуется написать немного кода. За вывод ошибки отвечает атрибут app:errorEnabled. Назначим текстовому полю тип клавиатуры и однострочный текст. При наборе текста после нажатия на клавишу Enter проверяем длину текста. Если текст меньше четырёх символов, то выводим сообщение об ошибке.

Текст ошибки выводится снизу от текстового поля.

Стиль для сообщения об ошибке можно стилизовать. Добавим новый атрибут.

В файле стилей res/values/styles.xml добавим новый стиль:

Теперь выводится другим цветом.

Расширенный вид стилей:

Применяем через атрибуты app:errorTextAppearance и android:theme.

Счётчик символов

С помощью атрибутов app:counterEnabled и app:counterMaxLength можно установить счётчик символов с указанием предела, который будет выводиться под текстовым полем.

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

Стиль применяется к атрибуту app:counterOverflowTextAppearance:

TextInputEditText

Казалось бы простой компонент, никаких трудностей не возникает. Но не торопитесь. Стоит повернуть устройства в альбомный режим, как текстовое поле растянется на весь экран и никакой подсказки вы не увидите. Возможно, это баг, который когда-нибудь починят. Но проблему легко решить, если вместо стандартного EditText использовать специальный компонент из библиотеки TextInputEditText:

Источник

Android studio textinputlayout style

Android TextInputLayout Tutorial

October 10, 2017

Android TextInputLayout makes it possible to display hint as floating label for EditText fields when it gets the focus.

Android TextInputLayout is a layout and can contain EditText widget or any of its descendants such as AppCompatEditText, AutoCompleteTextView, EmojiEditText, ExtractEditText, GuidedActionEditText, and SearchEditText.

TextInputLayout shows hint of child as label when hint is hidden. In addition to support for label, TextInputLayout also supports showing error message, password visibility toggling for password field, and character counter.

TextInputLayout Dependency

To use TextInputLayout in your application, you need to first add dependency to your project as shown below. TextInputLayout is part of android design library.

TextInputEditText with TextInputLayout

TextInputEditText is a subclass of EditText. It has been created to be used with TextInpputLayout so that layout can control the style of input field.

TextInputLayout TextInputEditText example

TextInputLayout Material Style

Below screen is the output of above layout when application theme is set to one of the app compact material themes. The pictures show hint when TextInputEditText is not focused and label when TextInputEditText is foucused and after value has been entered.

TextInputLayout Error

TextInputLayout supports error message. Using this feature, you can inform user about incorrect input for edit text fields by setting error message on TextInputLayout and display on UI.

When error needs to be displayed for a particular EditText, you need get parent TextInputLayout object and call setError method on it passing error message as an argument to it.

TextInputLayout set error

TextInputLayout remove error

Once error message is set on TextInputLayout object, it stays until it is removed. To clear or remove TextInputLayout error message, you need to call setError method passing null or empty message, in the above code else condition removes error message.

TextInputLayout error output

Android TextInputLayout Character Counter

TextInputLayout supports counter feature with which it can display number of characters entered into the input field. To enable counter, you need to call setCounterEnabled method passing boolean value true to it in the code or set counterEnabled xml attribute.

Note, to use attributes of TextInputLayout in xml layout, you need to define name space for android.support.design by setting it to android res-auto schema url as shown below.

TextInputLayout character counter output

Android TextInputLayout Password Visibility Toggle

TextInputLayout supports password visibility toggle feature with which user can toggle password visibility. This feature is applicable to password EditText fields. To enable password visibility toggle, you need to call setPasswordVisibilityToggleEnabled method passing boolean value true to it in the code or set passwordToggleEnabled xml attribute.

Читайте также:  Файловые обменники для андроид

User can click password visibility toggle button to see password in plain text or disguised form.

You can customize password visibility toggle button by setting setPasswordVisibilityToggleDrawable attribute to your custom drawable.

TextInputLayout Custom Material Style

You can define custom material style and change color of hint and edit text underline color by setting colorControlActivated, counter color by setting textColorSecondary, error message color by setting colorControlNormal and password visibility button tint by setting colorForeground.

About

Android app development tutorials and web app development tutorials with programming examples and code samples.

Источник

TextInputLayout Styling

Today, with the material components, we have at least 3 out of box implementations of input layout: Default, FilledBox, and OutlinedBox. And we want to briefly walk through their styling:

If you are looking for a brief solution you can use this table. Below you can find the description of each of these parameters in detail.

Hint color

Hint color could be set via “android:textColorHint” parameter of TextInputLayout. This parameter also changes the label default color (label focused color could also be changed in other ways). Let’s set a purple color (#673AB7) as an example.

Label, Helper and Error

Such parameters as “app:hintTextAppearance”, “app:helperTextTextAppearance” and “app:errorTextAppearance” together with all the necessary text parameters of styles.xml should be used to customize labels, helpers and errors in TextInputLayout. The parent of the text appearance style should be TextAppearance.AppCompat or some of its children.

Also, please keep in mind the following:

  • “ app:hintTextAppearance” affects the focused label color and label size in any state;
  • when an error is shown, the bottom/border line will have the color indicated in the “android:textColor” parameter of errorTextAppearance. This color will be changed to the default once the error is removed.

Here is the TextAppearances for error and helper that was used in the above shown TextInputLayouts:

Fonts

Fonts of all elements except inputted text (label, hint, error, and helper) could be easily changed in the program via the typeface parameter of TextInputLayout. We have done it in the following way:

Spaces

Label’s, Helper’s and Error’s spaces are connected to the EditText in the TextInputLayout. So, to increase or decrease spaces between the error/helper messages and bottom line/border you should use “android:layout_marginBottom” parameter, between the label and the top of the text, or add some space on the start of the error, helper and the label, and you should set positive or negative padding to the EditText. But you should understand that this will affect the text inside the InputLayout so, it would be better if horizontal spaces were symmetric from both sides.

As an example, let’s increase space above the errors for Default and OutlinedBox input layouts and decrease for FilledBox input layout. Also, let’s add some extra space at the start of the input layouts.

Bottom line color

Bottom line color could be changed with “app:backgroundTint” attribute of EditText view. Pay attention to the prefix, “app:” that makes this parameter back-compatible and useful even for Android API 16.

As for the OutlinedBox, it does not have the bottom line but has an outline instead. To change its color we should use “app:boxStrokeColor” parameter, but this parameter changes stroke color in the focused state only. Changing the default state of the stroke is a bit tricky. We should override mtrl_textinput_default_box_stroke_color color. The line below should be added to the color.xml file:

Let’s make the bottom line and the outline stroke color purple (#673AB7) as well.

Box background-color

This element is present in Filled and Outlined input layouts and can be changed via “app:boxBackgroundColor” parameter. Let’s change this parameter to the transparent purple (#26673AB7) only for FilledBox input layout.

Cursor and Selection

Finally, we get to the most interesting part — how to change the cursor and the selection handles. Most of you have already tried to use “app:textSelectHandle” parameters, that allow changing the drawable of the cursor handle and selection left and right handles. But how to change the color without drawing custom drawables and without changing the main application colors? It is not the secret that the cursor and handles color, as well as label color in focus mode, take their color from the AppTheme “colorAccent”. Of course, we can change it for the whole project but it is not obligatory. We can just use ThemeOverlay and change the “colorAccent” for a single view. We should inherit our style from ThemeOverlay.AppCompat and set it as the “android:theme” parameter of the view and that is all. As for the selection highlight, you can change it via android:textColorHighlight of the EditText.

In the example above was used android:color/holo_blue_light:

So, my final layout looked like this:

colors.xml includes the following colors:

styles.xml includes the following styles:

Tap the 👏 button if you found this article useful!

Читайте также:  Топ лучших андроид телефонов 2021

About the Author
Dmytro is Android Developer at OmiSoft, whose inner perfectionist does not allow to be content with mediocre results but forces him to move forward to excellence.

Need an Android mobile app with clean & maintainable code? Click here to get an estimate! Or find us on Facebook and Twitter.

Источник

Creating a Login Screen Using TextInputLayout

Introduction

In this tutorial, I will talk again about Material Design. Google I/O 2015 was an important event for every Android developer and design was of course part of the discussion.

Google has realized that backward compatibility is the trickiest part of the material design implementation. Sure, support libraries, such as appcompat-v4 and appcompat-v7, are part of the solution. However, Theme.AppCompat doesn’t implement every material item used in Google’s official applications. One of the features that is not present in the AppCompat theme is the possibility to position a floating label on top of an EditText widget. You can see what I mean in the below example.

During Google I/O 2015, the Android team released a brand new support library, the Design Support Library. It comes in very handy for this kind of problem. This tutorial will show you how to use the new TextInputLayout widget that’s included in the Design Support Library.

1. Implementing TextInputLayout

Step 1: Create a New Project

In Android Studio, choose New > New project from the File menu. Enter the required information to configure the project and create the project. In my example, I targeted the project to API 7, which is the minimum API level supported by the Design Support Library. By targeting such a low API level, your app will run on almost every Android device. I’ve named the main activity LoginActivity and its layout file activity_login.xml.

After setting up the project, remove in the main activity the onCreateOptionsMenu and onOptionsItemSelected method that are automatically generated by Android Studio. The login screen we’re about to create doesn’t need a menu so it’s fine to delete these methods. Remember also to delete the XML menu file that lives in the res/menu folder.

Step 2: Import the Support Libraries

To use the TextInputLayout widget, you have to import two libraries. The first one is appcompat-v7, which ensures that the material styles are backward compatible. The second one is the Design Support Library.

In your project’s build.gradle file, add the following lines in the project’s dependencies:

If Gradle doesn’t automatically ask you to synchronize your project, choose Make module ‘app’ from the Build menu or press F9. By doing so, the Android Studio build system will automatically fetch the necessary resources and you will be able to import any required classes.

Step 3: Design the User Interface

The user interface of this project is very simple. It shows a welcome label (which can be easily replaced by a logo if you have one) and two EditText elements, one for the username and one for the password. The layout also includes a button that triggers the login sequence. The background color is a nice, flat, light grey.

Another important detail worth remembering is the correct setting of the inputType attribute of the EditText elements. The inputType of the first EditText element should be set to textEmail while that of the second one should be set to textPassword . This is what the layout should look like.

You may also want to get rid of the app bar, previously known as the action bar, by editing the style.xml file as shown below.

Step 4: Using TextInputLayout

We have finally arrived at the most interesting part of this tutorial. A TextInputLayout widget behaves exactly as a LinearLayout does, it’s just a wrapper. TextInputLayout only accepts one child element, similar to a ScrollView . The child element needs to be an EditText element.

Note that I specified another parameter in the EditText item, a hint . As you already know, this attribute allows you to show a custom hint when there’s no content in the EditText . Once the user starts typing, the hint disappears. This isn’t great, because they lose context of the information they are entering.

Thanks to TextInputLayout , this won’t be a problem anymore. While the EditText alone will hide the hint after the first character is typed, when wrapped in a TextInputLayout the hint will become a floating label above the EditText . A nice material animation is included too.

Next, let’s do the same for the password field.

If you run the application now, nothing will happen. Sure, the EditText hint attribute will behave as expected. However, there’s no material animation and no floating labels. Why is that? We’re still missing some code to make everything work.

Step 5: Setting Hints

Below the setContentView method, initialize the references to the TextInputLayout views.

To animate the floating label, you just need to set a hint, using the setHint method.

And you’re done. Your login screen now properly follows the material design guidelines. Run the application to see your beautiful login screen.

2. Handling Errors

Another nice feature of TextInputLayout is the way it can handle errors. By validating the input, you prevent users from misspelling their email address or entering a password that is too short.

Читайте также:  Что такое саг android

With input validation, incorrect credentials would be processed by the backend, errors would be generated and sent to the client, and shown to the (waiting) user. A considerable loss of time and a poor user experience. You should check the user’s input before sending it to the backend.

Step 1: Implementing the onClick Method

You first have to handle the button click. There are plenty of ways to handle button clicks. One of them is by writing a custom method and specifying it in your XML file via the onClick attribute. I prefer setOnClickListener , but it’s really just a matter of personal taste.

We know that if this method is called, the user doesn’t need the keyboard anymore. Unfortunately, Android doesn’t hide the virtual keyboard automatically, unless you tell it to. Call hideKeyboard in the onClick method body.

Step 2: Validating Input

Before setting the error labels, we need to define what’s an error and what isn’t. We’re assuming that the username must be an email address and we want to prevent users from entering an invalid email address.

Validating an email address is a little bit complex. We have to rely on regular expressions. You can use the Apache Commons library too if you wish.

I’ve written the following regular expression, using the guidelines suggested by Wikipedia about email validity.

The meaning of this regular expression is quite simple. It’s comprised of three capturing groups. The first one matches the letters of the alphabet (upper and lower case), numbers, and a series of accepted symbols. Because of the + quantifier, this group matches a string that’s composed of at least one character.

Next, there’s the @ symbol, which is of course required in every email address. The second group accepts only letters, numbers, and hyphens. The length also needs to be at least one ( ]+ ).

Finally, there’s the last group, which contains a dot and whose purpose is matching subdomains and the TLD. Its quantifier is a star, * , which means that this group looks for a string whose length can be zero or more. In fact, email addresses with a domain, but no TLD, are actually valid.

Since we want to validate a String , we have to rely on Pattern and Matcher classes, included in the java.util.regex package. Import these classes in your activity and then implement the following method:

The validation of the password field is much simpler. Most organizations implement different policies for password validity, but everyone imposes a minimum length. A reasonable rule of thumb is that the password should never be shorter than six characters.

Step 3: Retrieving Data

As I said, TextInputLayout is just a wrapper, but unlike LinearLayout and ScrollView , you can get its child element using a specific method, getEditText . There’s no need to use findViewById .

If TextInputLayout doesn’t contain an EditText , getEditText returns null so be careful of a NullPointException .

Step 4: Showing Errors

TextInputLayout error handling is easy and fast. The required methods are setErrorEnabled and setError .

setError sets a red error message that will be displayed below the EditText . If the parameter passed is null , the error message is cleared. It also changes the color of the whole EditText widget to red.

setErrorEnabled enables the error functionality. This directly affects the size of the layout, increasing the lower padding to make room for the error label. Enabling this functionality before setting an error message via setError means that this layout will not change size when an error is displayed. You should do some tests combining these two methods so that you actually see what I am talking about.

Another interesting fact is that if the error functionality has not been enabled yet and you call setError passing a non-null parameter, then setErrorEnabled(true) will be automatically called.

Now that we have defined what’s right and what’s wrong, and we know how to retrieve data and display possible errors, the implementation of the onClick method becomes trivial.

I’ve added a doLogin method, but it’s currently empty since this is beyond the scope of this tutorial.

3. Styling

You might want to do one last thing, changing the color of the TextInputLayout widget. By default, the AppCompact theme sets it to green, but quite often this color conflicts with your color palette.

Google wrote the Design Support Library very well. Every widget’s color is drawn directly from the theme’s colors, specified in your style.xml file. Just open it and add the colorAccent item to your active theme to change the form’s color scheme.

Conclusion

In this tutorial, we saw how to implement the new layout item TextInputLayout , thanks to the just introduced Design Support Library.

The design paradigm that this widget implements allows users to never never lose context of the information they are entering and it was actually introduced by Google last year, along with Material Design.

At that time, there was no support library giving developers the possibility to put this widget into action in their projects, until Google I/O 2015. Now, if your application expects some sort of data input, you will finally be truly material design compliant.

Источник

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