Реализиране на приложение с начално меню и индивидуални екрани. / Creating an application with a home screen and additional screens.
1. Въведение
- В рамките на това упражнение ще се проследи процеса по създаване на начално меню за приложението и ще се представи метода за обвързване на бутоните на менюто с отделни екрани.
2. Цел на упражнението
- Създаване и преглед на ново приложение;
- Дефиниране на екранна подредба за основното меню и добавяне на функционалност за бутоните;
- Създаване на intent елементи за преход между екранните на приложението;
- Създаване на два допълнителни екрана и обвързването им с функциите на бутоните;
- Преглед на приложението посредством симулатор на смартфон.
3. Създаване и преглед на ново приложение в зависимост от ориентацията на устройството
- Стъпка 1. – Създаването на ново приложение може да стане по познатия начин от предходното упражнение. От началният екран на Android Studio (ако Android Studio директно отвори последния проект, трябва да го затворите за да стигнете до началния екран), изберете “New project”. На следващия екран, изберете “Empty Activity”.
1. Introduction
- This exercise will follow the process of creating a home screen for the application and will present the method of linking the menu buttons to additional screens.
2. Exercise goals
- Creating and viewing a new application;
- Defining a screen layout for the main screen and adding functionality for the buttons;
- Creating intent elements for transition between application screens;
- Creating two additional screens and linking them to the functions of the buttons;
- Viewing the application using a smartphone simulator.
3. Creating and viewing a new application depending on the orientation of the device
- Step 1. – Creating a new application can be done in the way you already know from the previous exercise. From the home screen of Android Studio (if the Android Studio directly opens the last project, you should close it to reach the home screen), select “New project”. On the next screen, select “Empty Activity”.

- На следващия екран, въведете следните настройки за проекта и изберете Next:
- Name: Lab6
- Package name: com.example.lab6
- Save location: C:\Users\your_username\AndroidStudioProjects\Lab6
- Language: Java
- Minimum SDK: API 19: Android 4.4 (KitKat)
След което натиснете Finish. ще генерира автоматично всички файлове и компоненти, от които ще се състои новото приложение. След приключване на този процес ще се изведе следния прозорец:
- On the next screen, enter the following project settings and select Next:
- Name: Lab6
- Package name: com.example.lab6
- Save location: C:\Users\your_username\AndroidStudioProjects\Lab6
- Language: Java
- Minimum SDK: API 19: Android 4.4 (KitKat)
Then click Finish. Android Studio will automatically generate all the files and components that the new application will contain. After completing this process, the following window will appear:
- Новосъздаденото приложение представлява познатото ви Hello World приложение от предишните упражнения.
Стъпка 2. – Стартиране на приложението. Използвайте клавишната комбинация Shift+10, за да стартирате приложението. Изберете съответния виртуален смартфон.
Стартирането на емулатора може да отнеме няколко минути!
Ако работната среда не разполага с активен виртуален смартфон създайте ново устройство, което да поддържа Android 4.4 KitKat
4. Дефиниране на екранна подредба за основното меню и добавяне на функционалност за бутоните
- Стъпка1. – Започнете да създавате основния екран за приложението като запазите RelativeLayout екранната подредба, но премахнете
- The newly created application is the same as the Hello World application from the previous exercise.
Step 2. – Use Shift + 10 to launch the application. Select the appropriate virtual smartphone.
It may take a few minutes to start the emulator!
If the work environment does not have an active virtual smartphone, create a new device that supports Android 4.4 KitKat
4. Define a screen layout for the main screen and add functionality to the buttons
- Step 1. – The main screen of the application should be created first by using the RelativeLayout. Remove the

- Стъпка 2. – Създайте първия бутон посредством <Button/> таг. Дефинирайте за бутона височина спрямо текста, ширина спрямо екранна на устройството и централно подравняване. Текста на бутона да се зарежда посредством променлива TBL, а при натискане на бутона да се изпълнява функцията Button1Click. Добавете идентификатор за бутона button1. Програмен код за създаването на бутона е представен на фигурата.
- Step 2. – Create the first button using the <Button/> tag. Define the button’s height to be relative to the text, width relative to the screen of the device and alignment to be central. The text of the button should be loaded using the TBL variable, and when the button is pressed, the Button1Click function should be called. An identifier button1 should be added for the button. Program code for creating the button is presented in the figure.

- Стъпка 3. – Добавете втори бутон. Дефинирайте за него идентификатор button2, задайте отново широчина на бутона отговаряща на широчината на екрана, височина на бутона еднаква с текстовото съдържание и централно подравняване. Задайте бутона да е под другия бутон с идентификатор button1. Текста на бутона да се зарежда посредством променлива JA, а при натискане на бутона да се изпълнява функцията Button2Click. Програмен код за създаването на бутона е представен на фигурата.
- Step 3. – Second button should be added. A button2 identifier should be defined for it, the width of the button should correspond to the width of the screen, the height of the button, the same as the text content and central alignment. The button should be set to be below the other button with ID button1. The text of the button should be loaded with the variable JA, and when the button is pressed to call the function Button2Click. Program code for using the button is presented in the figure.

- Прегледайте реализацията на програмния код чрез натискане на бутона Preview.
- Review the implementation of the program code by pressing the Design button.

5. Добавяне на функционалност за бутоните
- Стъпка 1. – За всеки от бутоните в предходната стъпка дефинирахме, че при натискането им ще се изпълни определена функция. Време е да разпишем и самите функции. Отворете файла MainActivity.java от папката java>com.example.lab6. Непосредствено преди функцията onCreate си дефинирайте двете функции Button1Click и Button2Click. Не забравяйте да натиснете Alt + Enter, за да добавите липсващите елементи в import секцията на документа.
5. Add functionality to the buttons
- Step 1. – For each of the buttons in the previous step, it was defined that pressing them will perform a certain function. It is time for this functions to be written. The MainActivity.java file should be opened. It is located in the folder: java>com.example.lab6. Just before the onCreate function, the two functions Button1Click and Button2Click should be defined. During this process, press Alt+Enter when prompted. This will import the missing items to the document’s import section.

- Както можете да видите от програмния код двете функции създават по един intent елемент, всеки от които е обвързан с отделен .class елемент за визуализация на екранна подредба. Самите екранни подредби не са създадени все още, но въпреки това във функциите са добавени startActivity() функциите, чрез които ще се извеждат на екрана новите екранни подредби.
6. Създаване на допълнителни екрани и обвързването им с функциите на бутоните
- Step 1. – Изберете папка res от лявата лента с елементи и създайте нов празен екран (New > Activity > Blank Activity). Кръстете елемента TBL.
- As you can see from the program code, both functions create an intent element, each of them is bound to a separate .class element for visualization of the screen layout. The screen layouts themselves have not been created yet, but the startActivity() functions have been added and they will call the corresponding screen layouts when a button is pressed.
6. Create additional screens and link them to the functions of the buttons
- Step 1. – Select the res folder from the left item bar and create a new empty activity (New> Activity> Empty Activity). Name the element TBL.


- Стъпка 2. – Повторете операцията от предходната стъпка и създайте още един елемент за визуализация на екранни подредби. Наименувайте елемента JA.
Стъпка 3. – Декларирайте елементите за визуализация на отделните страници. За всяка страница трябва да имате три елемента. Първият елемент е заглавие, което да се зарежда посредством променлива от тип string и да се подравнено централно. Под заглавието трябва да е вторият елемент – изображение, което да е подравнено централно. Третия елемент за страницата трябва да е поле за скролиране, което да съдържа основния текст за страницата.
- Step 2. – Repeat the operation from the previous step and create another empty activity. Name the element JA.
Step 3. – Declare the visualization elements of the individual pages. You must have three items for each page. The first element is a header to be loaded using a string variable and centered. Below the title should be the second element – an image that is centered. The third element for the page should be a scrolling field that contains the main text for the page.


- Стъпка 4. -След дефинирането на отделните елементи на екранните подредби е необходимо да се създадат и текстовите и графичните елементи. Добавете във файла strings.xml информация за TBL, TBLText, JA и JAText.
- Step 4. – After defining the individual elements of the screen layouts, it is necessary to create both text and graphic elements. Add information about TBL, TBLText, JA, and JAText to the strings.xml file.

-
Стъпка 5. – Последната стъпка преди стартирането на приложението е да добавите изображенията към проекта.
Добавете следните изображения: https://imgur.com/z4yL6AJ, https://imgur.com/PyW6g66 в папката на проекта:
C:\Users\your_username\AndroidStudioProjects\Lab6\app\src\main..
..\res\drawable
и ги преименувайте на tbl.jpg и ja.jpg.
Стъпка 6. – Стартирайте процеса по компилиране и изпълнение на приложението (Shift+F10). Прегледайте приложението и анализирайте функционалността му.
-
Step 5. – The last step before starting the application is to add the images to the project.
Add the following images: https://imgur.com/z4yL6AJ, https://imgur.com/PyW6g66 to the project image folder:
C:\Users\your_username\AndroidStudioProjects\Lab6\app\src\main..
..\res\drawable
and rename them to tbl.jpg and ja.jpg.
Step 6. – Start the process of compiling and running the application (Shift + F10). Review the application and analyze its functionality.

- Стъпка 7. – Добавете трети бутон и трети елемент за визуализация на екранна подредба.
Вие успешно приключихте това упражнение и създадохте приложение с меню и различни екрани за мобилно устройство!
- Step 7. – Add a third button and a third screen layout item.
!!CONGRATULATIONS!!
You have successfully completed this exercise and created an application with a menu and various screens for a mobile device!
