Android studio login activity как использовать

Android studio login 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:

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

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

Источник

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

Читайте также:  Android usb debugging как включить

What about the results? let’s coding (follow step by step)

  1. 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

Источник

Пример и объяснение: Android (Studio) Login Activity шаблон генерируется активность

Я хотел реализовать форму входа в мое приложение,поэтому я попытался использовать код, сгенерированный мастером Android Studio для нового действия типа формы входа. я думаю, что код, сгенерированный Eclipse, почти такой же.

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

также я заметил, что форма «регистрация» не была создан.

посмотрев немного и проанализировав код, я, наконец, получил его работу:)

см. Мой ответ ниже.

1 ответов

Шаг 1: сделать логин успешным и перейти к основной деятельности

для того, чтобы действие входа в систему завершилось ошибкой при использовании неправильного пользователя / пароля, и перейти к основному действию при успешном выполнении, вам необходимо внести следующие исправления в сгенерированный код:

Читайте также:  50 дней до моего для андроид

переместите следующий код из основного действия в раздел 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 нет в БД, он предложит зарегистрировать его, в противном случае он проверит электронную почту против пароля.

Источник

Android Studio – LoginActivity – Add Login Activity to Android Project

Android Studio – LoginActivity is a pre-defined Activity we can add to our Project in Android Studio. In this article, I am going to explain, add LoginActivity and launch it when we Run the Application.

Step 1. Open our Android Project “MyApp“, which we have created in our Previous Article “Android Studio : Create Android Project“.

Step 2. Lets’ add “Login Activity” to our Android Project “MyApp“. We already have a “Main Activity” which is displaying the “Hello, World!” message, when we Run the Project.

In addition to the “Main Activity“, we are going to add “Login Activity“.

Right-click on the Android view (where we are seeing the list of files); Android Studio will display the context menu. Select New menu item -> select Activity menu item -> and then select “Login Activity” menu item to start adding an Activity to the Project.

Android Studio – New LoginActivity

Step 3. Android Studio will open the “Configure Activity” dialog. Keep the same default values in:

Activity Name: LoginActivity

Layout Name: activity_login

Title: Sign in

Package name: com.codesteps.david.myapp

Source Language: Java

Click on the “Finish” button to add the “Login Activity” activity to the “MyApp” Project.

Step 4. You will see, “activity_login.xml” is added under res/layout. And LoginActivity class is added under java / com.codesteps.david.myapp.

Android Studio, automatically starts analyzing the code and it will display the report; once the Analysis is completed.

To me, it displayed a “13 warnings found” message; after the analysis was completed. We will look into these later.

Step 5. Lets’ Run the Project, and observe that; again you will see the “Hello, World!” message. But we have added “Login Activity” to display the login page. Why it is not showing.?

Читайте также:  Android как поменять мелодию звонка

In order to show our Activity, when we Run the Project; we should set our Activity as a LAUNCHER. LAUNCHER Activities will first appear when we launch the Application.

Step 6. Open AndroidManifest.xml file which is under app/manifests. This manifest file contains activities, and the attributes, actions, categories, etc.

Observer that, MainActivity is with the LAUNCHER category. And the MAIN action is defined for it.

What we need to do now is; remove or comment on these elements from “MainActivity” and add them to our “LoginActivity“.

Once the changes are done, save the file “AndroidManifest.xml“. After the changes, it looks like below:

Step 7. Re-run the Project and observe that; now our “LoginActivity” is shown when we launch the Application.

Android Studio – LoginActivity Launched

I am closing this Article here. Will discuss more Android Programming in my upcoming Articles.

I hope you liked this article. Please post the feedback through the below Comments.

Источник

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.

Источник

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