- Login activity android studio как пользоваться
- Пример и объяснение: Android (Studio) Login Activity шаблон генерируется активность
- 1 ответов
- Шаг 1: сделать логин успешным и перейти к основной деятельности
- Шаг 2: разрешите регистрацию, сохраните вход в базу данных и проверьте учетные данные vs DB
- Login Activity in Android Studio – Kotlin & Java
- 1. Import Material Design Library In Android Studio
- 2. Login Activity UI XML Design
- Login Activity Kotlin Code (For Kotlin Project)
- Login Activity JAVA Code (For JAVA Project)
- How to Create User Interface Login & Register with Android Studio
- Adjustment of several layouts :
- Connect fragments with viewpager
- Example and explanation: Android (Studio) Login Activity Template generated activity
- 1 Answer 1
- Step 1: Make Login successful and advance to main activity
- Step 2: Allow registration, store login into the database and check credentials vs DB
Login activity android studio как пользоваться
В этом уроке мы продолжим увеличивать свои способности в настройке пользовательского интерфейса своих приложений и оборудовать их все более серьезными вещами. На этот раз мы оснастим свое Android приложение функцией входа в приложение по вводу логина и пароля. Это может пригодится для многих приложений, да и просто интересно, как это делается. Все довольно просто, ничего сложного в реализации этой возможности не будет.
Мы сделаем приложение, при запуске которого нужно будет выполнить вход с помощью ввода логина и пароля — если данные введены верно мы попадаем на другой экран, если не правильно, то видим сообщение об ошибке.
Здесь пригодится вспомнить простенький урок о переходе между двумя экранами, этот прием встречался уже неоднократно, поэтому разъяснений по нему делать уже не буду.
Создаем новый проект, выбираем Blank Activity. Для начала создадим пользовательский интерфейс для приложения. Он будет состоять из полей ввода логина/пароля и кнопки для совершения входа. Открываем файл activity_main.xml и добавляем туда следующее:
Мы получили вот такой вид пользовательского интерфейса:
Сразу разберемся со вторым экраном, на который будет совершаться переход в случае успешного ввода логина и пароля. Создаем новый класс по имени Second.java:
И соответствующий ему layout файл по имени second_activity.xml:
Ну а теперь переходим к файлу основному MainActivity.java. Основной процесс будет происходить в методе обработки нажатия кнопки «Войти». В нем мы сравниваем введенные логин и пароль со словом admin и в зависимости от их совпадения или не совпадения настраиваем дальнейшие действия. Если введены логин и пароль admin, то высвечивается Toast сообщение об успехе входа и выполняется переход на второй экран с помощью Intent. Если данные введены не верно, то высвечивается сообщение с ошибкой, а после 3 неудачных попыток появляется надпись, что количество попыток исчерпано, а кнопка «Войти» становится неактивной. Итак, чтобы реализовать сказанное, открываем файл MainActivity.java и добавляем в него следующий код:
Кстати, не забудьте добавить вторую activity в файл манифеста AndroidManifest.xml:
Проверяем работоспособность своего творения:
Вот так, все отлично работает, теперь мы можем сделать свое приложение насколько крутым, что им смогут пользоваться только знающие данные логина и пароля для входа.
Источник
Пример и объяснение: Android (Studio) Login Activity шаблон генерируется активность
Я хотел реализовать форму входа в мое приложение,поэтому я попытался использовать код, сгенерированный мастером Android Studio для нового действия типа формы входа. я думаю, что код, сгенерированный Eclipse, почти такой же.
к сожалению, сгенерированный код не дал ожидаемого результата: я создал красивую простую форму входа, но с правильным или неправильным паролем она не перемещается из формы входа.
также я заметил, что форма «регистрация» не была создан.
посмотрев немного и проанализировав код, я, наконец, получил его работу:)
см. Мой ответ ниже.
1 ответов
Шаг 1: сделать логин успешным и перейти к основной деятельности
для того, чтобы действие входа в систему завершилось ошибкой при использовании неправильного пользователя / пароля, и перейти к основному действию при успешном выполнении, вам необходимо внести следующие исправления в сгенерированный код:
переместите следующий код из основного действия в раздел LoginActivity:
затем измените LoginActivity.java и сделайте следующее изменения:
внутри doInBackground метод, в конце заменить возвращаемое значение true to false
затем на onPostExecute Метод, Добавьте новое намерение после finish(); :
теперь логин должен быть успешным, используя один из следующих user:password данные:
другое user:password try должен указать неверный пароль и оставайтесь на странице входа.
Шаг 2: разрешите регистрацию, сохраните вход в базу данных и проверьте учетные данные vs DB
теперь мы получим данные для входа из базы данных (SQLite) вместо статической переменной. Это позволит нам иметь более 1 пользователя, зарегистрированного на устройстве.
сначала создайте новый User.java класс:
затем создайте или обновите помощник SQLite ( DBTools.java в моем случае) класс:
Примечание: DB_VERSION используется для обнаружения обновления / понижения схемы БД;)
затем измените LoginActivity.java следующим образом:
добавить следующий импорт:
добавить новую переменную:
удалить DUMMY_CREDENTIALS переменной.
на attemptLogin метод, добавить контекст при вызове UserLoginTask :
замените внутренний класс UserLoginTask следующим кодом:
на strings.xml , добавить:
надеюсь, я ничего не забыл. Это сработало отлично для меня: D
если email нет в БД, он предложит зарегистрировать его, в противном случае он проверит электронную почту против пароля.
Источник
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.
Источник
How to Create User Interface Login & Register with Android Studio
ok, this is my first article in Medium. In this section, I want to share with you about the User Interface on Android and we will create a Login page and a Register page. Some components that I will use:
1. Viewpager
2. Fragment
3. Edittext
4. Button
5. Textview
6. Imageview
What about the results? let’s coding (follow step by step)
- Of course we must already have an Android Studio. if not, you can download it first on the official Android Studio website. If you already have one, please open your Android studio.
2. We create a new project by clicking “Start a new Android Studio project”. Fill in the application name column with “LoginApp”, then click next.
3. Select the minimum SDK you need or want, then click next.
4. Select “Empty Activity” and click next. After that, the “Activity Name” and “Layout Name” columns will appear, in this section just leave it like that, then click finish.
After you click finish, Android Studio will make you an Application with the name “LoginApp”.
After the application is successfully built, you can simply make adjustments to the following sections:
Open the colors.xml file in app/res/values/colors.xml, and change it like this:
Create a folder with the name “font” in the res folder, by right clicking on the res directory, select new / directory and name it “font”. After that, copy this font into font directory. (download the font 1 and font 2).
Create some Drawable Resource File in the drawable directory, by right-clicking on the drawable directory, select new / Drawable Resource File.
After that open file styles.xml and change like this :
Add the theme property in the Main Activity in the manifest, in the app / manifests / AndroidManifest.xml folder
So the AndroidManifest.xml file will be as follows:
After all the steps above are done, then make 2 fragments with the name fragment_login and fragment_register in the layout directory, by right-clicking on the layout directory, New/Fragment/Fragment (Blank)
Uncheck:
include fragment factory methods? and include interface methods?
Adjustment of several layouts :
change the activity_main.xml layout, fragment_login.xml and fragment_register.xml so that it will be as below
Open the strings.xml file in the res / values / strings.xml directory and change it to something like the following :
So that the overall structure of the project will be as follows :
Connect fragments with viewpager
Create an inner class in the MainActivity.java class with the name AuthenticationPapterAdapter. This class is a derivative of the FragmentPagerAdapter class and serves to connect Fragments with ViewPager,
Then call the class in the onCreate() method in MainActivity.java and connect with viewpager
So the MainActivity.java class will be like this
The display of the final application will be like this
Источник
Example and explanation: Android (Studio) Login Activity Template generated activity
I wanted to implement a login form in my app, so I tried to use the code generated by the Android Studio Wizard for a new Activity of type Login Form. i think that the code generated by Eclipse is almost the same.
Unfortunately, the generated code did not provide the expected result: I created a nice simple login form, but with correct or wrong password, it does not move from the login form.
Also I noticed that no «Register» form was created.
After looking a bit, and analyzing the code, I finally got it working 🙂
See my response below.
1 Answer 1
Step 1: Make Login successful and advance to main activity
To have the login activity to fail when wrong user/password is used, and go to main activity when successful, you need to make the following corrections to the generated code:
Move the following code from you main activity to the LoginActivity section:
Then edit the LoginActivity.java and do the following changes:
Inside doInBackground method, at the end replace the returned value from true to false
Then on the onPostExecute method, add a new intent after the finish(); :
Now login should be successful using one of the following user:password credentials:
Other user:password try should state incorrect password and stay on Login page.
Step 2: Allow registration, store login into the database and check credentials vs DB
We now will get Login info from database (SQLite) instead of static variable. This will allow us to have more than 1 user registered on the device.
First, create a new User.java class:
Then create or update your SQLite helper ( DBTools.java in my case) class:
Note: DB_VERSION is used to detect upgrade/downgrade of the DB schema 😉
Then modify the LoginActivity.java as follow:
Add the following imports:
Add a new variable:
Remove DUMMY_CREDENTIALS variable declaration.
In attemptLogin method, add context when calling UserLoginTask :
Replace the internal UserLoginTask class with the following code:
In strings.xml , add:
I hope I did not forget anything. It worked fine for me 😀
If email is not present in the DB, it will propose to register it, otherwise it will check the email versus the password.
Источник