Създаване на приложение с интерактивен графичен потребителски интерфейс / Create an application with an interactive graphical user interface
1. Въведение
- В рамките на това упражнение ще се проследи процеса по създаване на интерактивен графичен интерфейс. Студентите ще упражнят получените до момента знания и ще затвърдят своите умения за разработване на приложения посредством Android Studio.
2. Цел на упражнението
- Създаване на ново приложение и добавяне на елементи от графичния интерфейс, като бутони и TextView полета;
- Затвърдяване на уменията по редактиране на екранната подредба чрез XML;
- Създаване на метод за обработка на натискането на бутон и за извеждане на съобщение на екрана на устройство при натискане на определен бутон;
- Редактиране на метода за промяна на съобщението, което се извежда;
3. Създаване на ново приложение, дефиниране на линейна екранна подредба и създаване на елементи
- Стъпка 1. – Създаването на ново приложение може да стане по познатия начин от предходното упражнение. От началният екран на Android Studio (ако Android Studio директно отвори последния проект, трябва да го затворите за да стигнете до началния екран), изберете “New project”. На следващия екран, изберете “Empty Activity”.
1. Introduction
- This exercise will follow the process of creating an interactive graphical interface. Students will practice the knowledge gained so far and will strengthen their skills for developing applications through Android Studio.
2. Exercise goals
- Creating a new application and adding GUI elements such as buttons and TextView fields;
- Strengthening the skills of editing the screen layout using XML;
- Creating a method for processing the pressing of a button and for displaying a message on the screen of the device when a certain button is pressed;
- Editing the method for changing the message that is displayed;
3. Creating a new application, defining a linear screen layout and creating elements
- 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: Lab4
- Package name: com.example.lab4
- Save location: C:\Users\your_username\AndroidStudioProjects\Lab4
- Language: Java
- Minimum SDK: API 19: Android 4.4 (KitKat)
След което натиснете Finish. ще генерира автоматично всички файлове и компоненти, от които ще се състои новото приложение. След приключване на този процес ще се изведе следния прозорец:
-
On the next screen, enter the following project settings and select Next:
- Name: Lab4
- Package name: com.example.lab4
- Save location: C:\Users\your_username\AndroidStudioProjects\Lab4
- 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. – Планираното за разработване приложение трябва да бъде реализирано посредством LinearLayout екранна подредба и трябва да съдържа два бутона и едно поле за извеждане на текстова информация (TextView). Създаването на това приложение ще е малко по-сложно, защото ще изисква дефиниране на нови цветове и размери, както и използването на вертикално разположение на елементите в екранната подредба. Завършеното приложение трябва да изглежда като това от фигурата.
-
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.
!!ATTENTION!!
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. Definition of the screen layout for the application
- Step 1. – The application planned for development must be implemented using a LinearLayout and must contain two buttons and one field for displaying text information (TextView). Creating this application will be a bit more complicated because it will require defining new colors and sizes, as well as using the vertical arrangement of the elements in the screen layout. The finished application should look like the one in the figure.

- Стъпка 2. – Започнете създаването на приложението с промяната на екранната подредба от ConstraintLayout на LinearLayout. Използвайте вертикална екранна подредба. Програмен код за създаването на екранната подредба е представен на фигурата.
- Step 2. – Start creating the application by changing the screen layout from ConstraintLayout to LinearLayout. Use a vertical screen layout. Program code for creating the screen layout is presented in the figure

- Стъпка 3. – Премахнете съществуващия към момента TextView елемент и преминете към създаването на елементите от екранната подредба. За пълната детайлна визуализация на елементите от екранната подредба ще е необходимо и да се дефинират и няколко нови символни последователности, както и един цвят и една нова променлива за размера на текста в текстовото поле. Резултата за екранната подредба трябва да изглежда като този от фигурата.
- Step 3. – Remove the currently existing TextView element and proceed to the creation of the elements from the screen layout. For the full detailed visualization of the elements of the screen arrangement it will be necessary to define several new strings, as well as one color and one new variable for the size of the text in the text field. The result for the screen layout should look like the one in the figure.

5. Дефиниране на нови ресурси за приложението
- Стъпка 1. – Отворете файла strings.xml. Променете наименованието на приложението (стойността на променливата app_name) на Hello Toast. Дефинирайте нова променлива променливата button_label_count със стойност Count. Дефинирайте друга нова променлива button_label_toast със стойност Toast. Както би трябвало да се досещате, това са текстовете, които ще се извеждат върху бутоните.
Дефинирайте трета нова променлива – count_initial_value със стойност 0. Това ще е първоначалната стойност за нашия брояч.
Последната нова променлива трябва да се казва toast_button_toast и трябва да е със стойност Hello Toast! (или произволен текст). Тази стойност ще се извежда на екрана при натискане на бутона Toast.
Финалната версия на файла с променливите трябва да изглежда както е показано на фигурата.
5. Definition of new resources for the application
- Step 1. – Open the strings.xml file. Rename the application (the value of the app_name variable) to Hello Toast. Define a new variable button_label_count with value Count. Define another new variable button_label_toast with the value Toast. As you might guess, these are the texts that will be displayed on the buttons.
Define a third new variable – count_initial_value with a value of 0. This will be the initial value for the counter.
The last new variable should be called toast_button_toast and its value should be Hello Toast! (or random text). This value will be displayed when the Toast button is pressed.
The final version of the strings file should look as shown in figure.

- Стъпка 2. – Отворете файла colors.xml. По подразбиране този файл съдържа само няколко цвята. Добавете параметър myBackgroundColor и дефинирайте цвят по избор. За нуждите на това упражнение е използван цвят с код #FFF043. Цветът purple_500 е използван за цвят на текста и за фон на бутоните, защото това е основния цвят на приложението. Това може да бъде проверено в themes.xml. Забележете, че Android Studio ви позволява да добиете представа как изглежда визуално цвета, като в този случай, дефинираният цвят е представен в сивото поле до кода.
Освен потребителски дефинираните цветове, Android Studio позволява и да се използват основните цветове, които са дефинирани в системата. Пример за това беше даден с дефиницията на втория бутон, където текста е определен да бъде с бял цвят посредством android:textColor=”@android:color/white.
- Step 2. – Open the colors.xml file. By default, this file contains only a few colors. Add a myBackgroundColor parameter and define a custom color. For the purposes of this exercise, a color with code #FFF043 was used. The color purple_500 was used for text color and for background of the buttons because it is the primary color of the application. This can be seen in themes.xml. Note that Android Studio allows you to get an idea of what the visual resource would look like, in this case the defined colors are presented in the gray field next to the code.
In addition to user-defined colors, Android Studio also allows you to use the primary colors that are defined in the system. An example of this was given with the definition of the second button, where the text is set to be white using android:textColor=”@android:color/white.


- Стъпка 3. – Създайте файла dimens.xml. В res/values папката чрез избирането на New -> Values resource file, създайте файла и му задайте име “dimens”.
- Step 3. – Create dimens.xml. Under the res/values folder with New -> Values resource file, create a file and set its name to “dimens”.


- В новосъздадения файл, дефинирайте нова променлива с наименование count_text_size. Тази променлива ще определя големината на текста за брояча. Дефинирайте стойност от 160sp за променливата
- In the newly create file, a new variable named count_text_size should be defined. This variable will determine the text size for the counter. The value should be set to 160sp.

- Стъпка 4. – Стартирайте приложението в емулатор. Ако сте изпълнили правилно всички стъпки и ако нямате някъде грешки, трябва да ви се стартира основен екран за приложението, който изглежда като този от фигурата.
Стъпка 5(optional): Ако ви се извежда следната грешка: The minCompileSdk (31) specified in a dependency’s AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties) is greater than this module’s compileSdkVersion (android-30). Файлът build.gradle трябва да бъде редактиран. compileSdk и targetSdk трябва да бъдат със стойност 31.
- Step 4. – Run the application in the emulator. If you have performed all the steps correctly and if you do not have any errors somewhere, the main screen for the application will be visualized, which looks like the one in figure.
Step 5(optional): If you get the following error while compiling: The minCompileSdk (31) specified in a dependency’s AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties) is greater than this module’s compileSdkVersion (android-30). The build.gradle should be edited. The compileSdk and targetSdk should be set to 31.


- Стъпка 6. – Както виждате бутона Toast се е слял с лентата със заглавието за приложението, което прави трудно неговото разпознаване. За да коригирате този проблем, а и за да направите приложението малко по-прегледно, дефинирайте отстъпи за екранната подредба. Добавете android:paddingBottom и android:paddingTop и им задайте стойности 16dp. Аналогично, добавете android:paddingLeft и android:paddingRight и им задайте стойности 16dp.
Стъпка 7. – Последната стъпка от процеса по дефиниране на визуалните елементи за приложението е да се добави обръщение към функциите за работа на бутоните. За бутона Toast дефинирайте параметър android:onClick с атрибут showToast, а за бутона Count добавете параметър android:onClick с атрибут countUp.
Финалната версия на програмния код и примерната визуализация на приложението са показани на фигурата.
- Step 6. – It is visible that the Toast button has merged with the title bar for the application, which makes it difficult to recognize. To correct this problem, and to make the application a little clearer, define indents for the screen layout. Add android:paddingBottom and android:paddingTop and set them to 16dp. Similarly, add android:paddingLeft and android:paddingRight and set them to 16dp.
Step 7. – The last step of the process of defining the visual elements for the application is to add a reference to the functions of the buttons. For the Toast button, define an android:onClick parameter with value showToast, and for the Count button, add an android:onClick parameter with value countUp.
The final version of the program code and the sample visualization of the application are shown in the figure.

6. Добавяне на функционалност за бутоните
- Стъпка 1. – Отворете файла MainActivity.java. Дефинирайте две нови променливи – mCount и mShowCount. Първата ще е от целочислен тип и трябва да е инициализирана със стойност 0. Това ще бъде брояча. Втората променлива трябва да е от тип TextView. На тази променлива ще присвоим стойността на TextView полето и ще я използваме за промяна на извежданата на екрана стойност. Сегмента от програмния код е даден на фигурата.
6. Add functionality for the buttons
- Step 1. – Open the MainActivity.java file. Define two new variables – mCount and mShowCount. The first will be of integer type and must be initialized with a value of 0. This will be the counter. The second variable must be of type TextView. We will assign the value of the TextView field to this variable and use it to change the value displayed on the screen. The segment of program code is given in figure 15. Use Alt+Enter to import the TextView class.

-
Стъпка 2. – Променете съдържанието на функцията onCreate, като добавите връзката между mShowCount и TextView полето от екранната подредба. Използвайте функцията findViewById с аргумент R.id.show_count.
- Step 2. – Change the content of the onCreate function by adding the link between the mShowCount and the TextView field of the screen layout. Use the findViewById function with the R.id.show_count argument.

- Стъпка 3. – Дефинирайте функционалността на бутона Count, като създадете нова функция countUp(View view). При извикване на тази функция (т.е. натискане на бутона), стойността за mCount трябва да се увеличава с едно, да се прави проверка дали променливата за извеждане на информацията (mShowCount) е инициализирана и има стойност, след което на тази променлива да се присвои стойността на mCount, но след като е била конвертирана в символен низ.
- Step 3. – Define the functionality of the Count button by creating a new countUp(View view) function. Use Alt+Enter to import View class. When calling this function (ie pressing the button), the value for mCount must be incremented by one, to check whether the variable for displaying information (mShowCount) is initialized and has a value, then the value of mCount to be assigned to mShowCount, but it has to be converted to a character string first.

- Стъпка 4. – Дефинирайте функционалността на бутона Toast, като създадете нова функция showToast(View view). Съдържанието на тази функция трябва да включва дефиниция на нов обект от тип Toast, който да визуализира на екрана съобщение посредством метода makeText. Този метод има три входни параметъра: контекстен идентификатор (в нашия случай ще е текущото приложение и за целта ще използваме this), планираното за визуализиране текстово съобщение и продължителността за престой на съобщението на екрана. С предефинираните атрибути LENGTH_SHORT и LENGTH_LONG можете да укажете дали съобщението да се показва съответно за 2 или 3.5 секунди. Дефинирането на Toast съобщението, подобно на дефиницията на процесите (т.н. intents) не предизвиква тяхното стартиране. За целта трябва да се изпълни функцията show(), както е указано на фигурата.
-
Step 4. – Define the functionality of the Toast button by creating a new showToast(View view) function. The content of this function must include the definition of a new Toast object to display a message on the screen using the makeText method. This method has three input parameters: the context identifier (in our case it will be the current application and we will use this parameter for this purpose), the text message planned for visualization and the length of time the message stays on the screen. With the predefined LENGTH_SHORT and LENGTH_LONG attributes, you can specify whether the message is displayed for 2 or 3.5 seconds, respectively. Defining a Toast message, like defining processes (so-called intents), does not trigger them. To do this, the show() function must be called as shown in the figure.

- Стъпка 5. – Стартирайте приложението и тествайте неговата функционалност.
7. Допълнително предизвикателство
- Стъпка 1. – Променете функцията showToast, така, че при натискане на бутона Toast със съобщението да се извежда стойността от TextView полето.
- Step 5. – Launch the application and test its functionality.
7. An additional challenge
- Step 1. – Change the showToast function so that when you press the Toast button the value from the TextView field to be displayed.

Вие успешно приключихте това упражнение и създадохте приложение с възможност за извеждане на съобщения на екрана!
You have successfully completed this exercise and created an application with the ability to display messages on the screen!
