Android studio pin code activity

Tutorial: PIN input view in Android

Today’s post will be about PIN-like view in Android. I’m sure that many Android developers would like to have it by default, me included. And so I wanted to show you how I handled the problem caused by lack of such view. But first, how should it look like? Well, it should like an input field where every character has it’s own box and while typing, characters should automatically populate those boxes. Sounds pretty easy, isn’t it? But later, when you think about all of the aspects, you will realize it’s not that simple at all…

First, I wanted to mention that this particular example is for text passwords (or text pin). The code for just numerical PIN view would be much easier. But it wasn’t the case with the app I was writing and I definitely needed the default keyboard. Because I could change my soft keyboard from text to numerical at any point of typing, I couldn’t have a collection of EditTexts because switching from one to another would have changed a keyboard either to text or numerical and I didn’t want that.

So, I had to think of something more flexible. And what I’ve done is created a collection of EditTexts AND another one which user wouldn’t normally see but which will actually take a focus and basically do the job for us.

OK, lets see some code!

Here’s the main.xml layout:

What you can see here is just a LinearLayout with some text label, five edit texts and one hidden below.
It is not even hidden, just a transparent 1dp width and height EditText. Edit texts for pin have its own style.

styles.xml

We want our characters aligned to center, cursor won’t be visible as we won’t edit one character separately but the whole PIN view at once. Max length each of those PIN inputs should be 1. minEms with value of 2 ensures the width of input won’t shrink or expand depending on character width.

Strings for this example project:

strings.xml

dimens.xml

And AndroidManifest.xml:

This project wasn’t tested on Android 2.x.x, so I just put a min SDK version to 14 (which is Android 4.0). You can try to run it on lower versions.

I have also used Theme.Holo.Light. It could have been any other theme, it’s just that I need EditText focusable and default backgrounds and they were adjusted for the Light theme. Why bother about those backgrounds? Because we will set it programmatically depending on focus and on characters typed in our PIN view. You will see when you will actually run this project 🙂 Just remeber, you need to have some gfx files 😉

Читайте также:  Как запретить доступ android

OK, so the most interesting part is the code!

Wow, a lot of code you might say! And yet, there’s is just enough for correct functioning 😉

We have init() method in which our edit texts are initialized, then we have onFocusChange() method. If user touches any of our pin edit texts, we should catch the focus of our hidden EditText and show soft keyboard. onKey() method checks if DEL key was pressed, then checks how many characters were typed and based on that sets our edit texts to empty. onTextChanged() method sets correct background based on text length and also sets characters we typed.

The last interesting thing here is MainLayout which is just a LinearLayout with overridden onMeasure() method. Why do you need this? Because when the keyboard is shown, we need to highlight the first PIN box (if it is not empty). This is just for a better UX, nothing more I guess…

And that’s all! A lot of code but the idea is quite clear. We have one EditText, which catches the focus and characters we type, everything else is just a programmatic trick 😉

Источник

[:ru]Защита андроид-приложения с помощью пинкода[:en]App lock library for Android[:]

[:ru]В этом видеоуроке реализуем блокировку приложения с помощью библиотеки AppLocker. Исходный код — ниже, под видео.

Для импорта библиотеки в проект добавьте строки в файл сборки build.gradle (Module: app):

Также понадобятся такие строковые ресурсы в файле res/values/strings.xml:

В главном пакете создаем класс приложения App.java, в котором инициализируем AppLocker:

Объявим класс App.java в манифесте в секции application:

Макет главного экрана activity_main.xml содержит две кнопки:

И код класса MainActivity.java, который унаследован от библиотечного класса LockActivity:

В методе onCreate объявлены кнопки и присвоен обработчик нажатия. В методе onClick определяем нажатую кнопку, а также содаем и отправляем интенты с наборами данных, вызывающие класс LockActivity. Последний отображает экран ввода для установки или смены пароля. В методе onActivityResult можно добавить нужное поведение приложения, в зависимости от того, какой интент пришел. Метод updateUI меняет текст на кнопках и делает кнопку смены пароля неактивной, если защита паролем отключена.

Исходный код библиотеки AppLocker — на странице в GitHub.[:en]In this video tutorial we implement application locks with AppLocker library. Source code — below, under the video.

Источник

Android studio pin code activity

LolliPin

A Lollipop material design styled android pincode library (API 14+)

To include in your project, add this to your build.gradle file:

Starting from version 2.1.0 we will have a different package name:

The password itself is not saved, only its hash using the SHA-1 algorithm. This hash is then saved on the SharedPreferences, allowing to verify that the user entered the right PinCode, without giving the possibility to retrieve it.

Once the user has enabled the password, he can also use his fingerprint scanner (using Google Api, not Samsung) to unlock his device.

Читайте также:  Виджет двойные часы для андроид определение пояса

If you want an example on how to use it, you can find an example app in this repo.

We are using a custom version of RippleView that contains a RippleAnimationListener. In order to be able to fetch this dependency, you need to add these lines into your main build.gradle file:

Overriding the AppLockActivity

In order to use the «Forgot» system, we let you extend the AppLockActivity class to provide your own way of handling the user behaviour in this case (logout, delete datas etc. )

Advised to be done by extending the Application, but can be done elsewhere. The method below provides a way to enable or disable the PinCode system:

Once enabled, you must extend «PinActivity» for every Activity you wish to protect.

Set up the PinCode

Whenever you want the user to set up his pin code, you need to request:

As soon as you enable the PinCode system, the Unlock screen will appear by itself when the user resume the app after a defined timeout. Please refer to the next section to know how to customize these values.

Some features are customizable:

The unlock timeout:

The pin length required:

The logo displayed at the top of the page:

The ignored activities:

For instance you got a login activity that you want to avoid getting the lock screen, you can ignore this activity by doing:

The AppLockActivity Layout:

By providing a custom layout to getContentView() you can alter how your AppLockActivity looks. However, you must include 4 required elements:

  • TextView with an id of pin_code_step_textview
  • TextView with an id of pin_code_forgot_textview
  • PinCodeRoundView with an id of pin_code_round_view
  • KeyboardView with an id of pin_code_keyboard_view

By supplying alternate drawable resources for app:lp_empty_pin_dot and app:lp_full_pin_dot you can custimize how it looks.

Источник

Android studio pin code activity

В этом уроке мы продолжим увеличивать свои способности в настройке пользовательского интерфейса своих приложений и оборудовать их все более серьезными вещами. На этот раз мы оснастим свое Android приложение функцией входа в приложение по вводу логина и пароля. Это может пригодится для многих приложений, да и просто интересно, как это делается. Все довольно просто, ничего сложного в реализации этой возможности не будет.

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

Здесь пригодится вспомнить простенький урок о переходе между двумя экранами, этот прием встречался уже неоднократно, поэтому разъяснений по нему делать уже не буду.

Создаем новый проект, выбираем Blank Activity. Для начала создадим пользовательский интерфейс для приложения. Он будет состоять из полей ввода логина/пароля и кнопки для совершения входа. Открываем файл activity_main.xml и добавляем туда следующее:

Мы получили вот такой вид пользовательского интерфейса:

Сразу разберемся со вторым экраном, на который будет совершаться переход в случае успешного ввода логина и пароля. Создаем новый класс по имени Second.java:

И соответствующий ему layout файл по имени second_activity.xml:

Читайте также:  Что делать когда украли андроид

Ну а теперь переходим к файлу основному MainActivity.java. Основной процесс будет происходить в методе обработки нажатия кнопки «Войти». В нем мы сравниваем введенные логин и пароль со словом admin и в зависимости от их совпадения или не совпадения настраиваем дальнейшие действия. Если введены логин и пароль admin, то высвечивается Toast сообщение об успехе входа и выполняется переход на второй экран с помощью Intent. Если данные введены не верно, то высвечивается сообщение с ошибкой, а после 3 неудачных попыток появляется надпись, что количество попыток исчерпано, а кнопка «Войти» становится неактивной. Итак, чтобы реализовать сказанное, открываем файл MainActivity.java и добавляем в него следующий код:

Кстати, не забудьте добавить вторую activity в файл манифеста AndroidManifest.xml:

Проверяем работоспособность своего творения:

Вот так, все отлично работает, теперь мы можем сделать свое приложение насколько крутым, что им смогут пользоваться только знающие данные логина и пароля для входа.

Источник

Login Activity in Android Studio – Kotlin & Java

In this tutorial, we will design a general Login Activity in Android Studio in both Kotlin & Java Android Programming languages. In this article, we are going to use Google Material Design guidelines to design the UI. And our EditText will be floating like it moves the hint above as heading when we start writing. We will also perform the validation of the inputs. You can use this code as a utility while designing Login Screens in your Apps. At the end of this tutorial, we will achieve the following design with input validations.

1. Import Material Design Library In Android Studio

In this article, we are going to TextInputLayout from Google Material Design for which we need to import Google Material design library. To import that add the following material design dependency in your app level build.gradle file.

2. Login Activity UI XML Design

Add the the following XML code in your Login Activity’s XML File.

Login Activity Kotlin Code (For Kotlin Project)

If you are developing your Activity in Kotlin then add the following code in your LoginActivity.kt file. otherwise for JAVA code please scroll down.

Login Activity JAVA Code (For JAVA Project)

If you are developing your Activity in JAVA then add the following code in your LoginActivity.java file.

As mentioned earlier we are using TextInputLayout from Google Material design library. And we are embedding our EditText inside TextInputLayout which makes our EditText floating. Like when we start writing in our EditText its Hint moves above and becomes a heading. In our Kotlin/JAVA code, we have a method validateInput() . It checks the format of Email and validates the password before actually calling your API on Server. In this article, we didn’t make server request, for that please read our next article.

That’s it. This is how to design a simple Login Activity in Android Studio.

Feel free to ask your questions or give suggestions in the comments section below.

Источник

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