Създаване и изпълнение на опростено приложение с графичен интерфейс за локално препращане на съобщения. / Creation and execution of a simple application with graphical interface for local message forwarding.
1. Въведение
- Целта на това упражнение е създаването и изпълнението на опростено приложение с графичен интерфейс. За целта ще се създаде нова екранна подредба (layout) използвайки XML, която ще включва текстово поле и бутон. Реализираното приложение ще реагира на натискането на бутона и ще изпрати съдържанието на текстовото поле към друг екран. Студентите ще затвърдят знанията си за работа с Android studio и ще придобият нови познания за структурата на приложенията и техните компоненти.
Графичния потребителски интерфейс за всяко Android приложение се изгражда посредством йерархия от обекти от тип View и ViewGroup. Обектите от тип View обикновено са пособия от графичния потребителски интерфейс, като например бутони или текстови полета. Обектите от тип ViewGroup са невидими контейнери, които дефинират подредбата на екрана на отделните елементи, като например вертикален списък с елементи или таблица. Android предоставя XML структура на кода, която отговаря на подкласовете View и ViewGroup и ви позволява да дефинирате собствени елементи от графичния интерфейс в XML посредством йерархия на елементите за графичния интерфейс (Фиг. 1). Екранните подредби представляват подкласове на всеки ViewGroup обект. В рамките на това упражнение ще се работи основно с линейната подредба на елементите – LinearLayout.
- The main goal of this exercise is the creation and execution of a simple application with a graphical interface. To do this, a new screen layout will be created using XML, which includes a text box and a button. The created application will respond to the push of a button and send the content of the text box to another screen. Students will improve their knowledge of working with Android studio and will gain new knowledge about the structure of applications and their components.
The graphical user interface for each Android application is built through a hierarchy of View and ViewGroup objects. The View object is typically item of the graphical user interface, such as buttons or a text box. ViewGroup objects are invisible containers that define the screen arrangement of individual items, such as a vertical list of items or a table. Android provides an XML code structure that corresponds to the View and ViewGroup subclasses and allows you to define your own GUI elements in XML through a hierarchy of GUI elements (Figure 1). Screen layouts are subclasses of each ViewGroup object. Within this exercise you will work mainly with the linear layout of the element – LinearLayout.

2. Цел на упражнението
- Създаване на ново приложение и дефиниране на линейна екранна подредба;
- Добавяне на елементи към работната среда – добавяне на бутон и поле за въвеждане на информация;
- Работа със стрингове;
- Създаване на действия и допълнителни работни екрани;
- Действия с intent елементи и визуализация на съобщения;
3. Създаване на ново приложение, дефиниране на линейна екранна подредба и създаване на елементи
- Стъпка 1. – Създаването на ново приложение може да стане по познатия начин от предходното упражнение. От началният екран на Android Studio (ако Android Studio директно отвори последния проект, трябва да го затворите за да стигнете до началния екран), изберете “New project”. На следващия екран, изберете “Empty Activity”.
- Creating a new application and defining a linear screen layout;
- Adding elements to the programing environment – adding a button and a field for entering information;
- Working with strings;
- Creating actions and additional screen layouts;
- Actions with intent elements and visualization of messages;
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: Lab2
- Package name: com.example.lab2
- Save location: C:\Users\your_username\AndroidStudioProjects\Lab2
- Language: Java
- Minimum SDK: API 19: Android 4.4 (KitKat)
След което натиснете Finish. ще генерира автоматично всички файлове и компоненти, от които ще се състои новото приложение. След приключване на този процес ще се изведе следния прозорец:
- On the next screen, enter the following project settings and select Next:
- Name: Lab2
- Package name: com.example.lab2
- Save location: C:\Users\your_username\AndroidStudioProjects\Lab2
- 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. – Дефиниране и създаване на линейна екранна подредба. В лявата страна на работното пространство се намират всички ресурси и компоненти на приложението. Изберете res > layout, след което изберете файла activity_main.xml и от горния десен ъгъл изберете Code View.
- The newly created application is the same as the Hello World application from the previous exercise.
Step 2. – Define and create a linear screen layout. On the left side of the workspace are all the resources and components of the application. Select res > layout, then select the activity_main.xml file and from the top right corner select Code View.

- Изведения на екрана xml файл съдържа елементите на примерното приложение и се използва за дефиниране на екранната подредба. Към текущия момент от време съдържанието на файла трябва да е съставено от ConstraintLayout елемент, съдържащ TextView компонент. Изтрийте елемента
- The shown xml file contains the elements of the demo application and is used to define the screen layout. At this time, the content of the file must be composed of a ConstraintLayout element containing a TextView component. Delete the

- Екранната подредба LinearLayout е подклас на ViewGroup елементите и дефинира вертикална или хоризонтална подредба на елементите, която се указва с атрибута android:orientation. Елементите, които са дефинирани в рамките на елемента LinearLayout ще се визуализират на екрана в последователността, в която са дефинирани в xml файла. Другите два атрибута, android:layout_width и android:layout_height, са задължителни за всички екранни подредби и указват големината на екрана. Поради факта, че LinearLayout е основната екранна подредба, то тя ще заеме целия екран, който е наличен за приложението, ако стойностите за двата атрибута са зададени на match_parent. С тези стойности се указва, че видимата площ за приложението трябва да заеме максималната възможна площ на екрана.
Стъпка 3. – Добавяне на текстово поле. След изпълнението на предходната стъпка реално на екрана на приложението няма да се изведат никакви елементи (единствения елемент за приложението беше
Подобно на всеки друг елемент от тип View и за EditText е необходимо да се добавят определени атрибути, с които да се окажат характеристиките на елемента. Изберете отново файла activity_main.xml и в рамките на
- The LinearLayout screen layout is a subclass of ViewGroup element and defines a vertical or horizontal arrangement of elements, which is indicated by the android:orientation attribute. The elements that are defined within the LinearLayout element will be displayed on the screen in the order in which they are defined in the xml file. The other two attributes, android:layout_width and android:layout_height, are required for all screen layouts and indicate the screen size. Due to the fact that LinearLayout is the main screen layout, it will occupy the entire screen that is available for the application if the values for both attributes are set to match_parent. These values indicate that the visible area for the application should occupy the maximum possible screen area.
Step 3: – Add a text box. After completing the previous step, no items will actually be displayed on the application screen (the only item for the application was
Like any other View element, EditText needs certain attributes to be added which define the characteristics of the element. Select the activity_main.xml file again and within the

- Атрибутите в елемента
Атрибут Android:id:
Този атрибут предоставя уникален идентификатор за всеки обект и може да се използва за извикването му от приложния код. Действията с обекта могат да включват изчитане и манипулиране на обекта, но и редица други. Символа @ е задължителен при обръщение към обекти в xml файлове. Непосредствено след този символ трябва да бъде упоменат и типа на данните (в този случай е id). След типът на данните се поставя наклонена черта, последвана от наименованието на ресурса (edit_message). Знака плюс (+) пред типа на ресурса е необходим само когато се дефинира идентификатор за ресурс за първи път. При компилиране на приложението SDK платформата ще използва този идентификатор за създаване на нов запис за ресурс във файла gen/R.java, като този ресурс ще се използва като указател за EditText елемента. Щом ресурса се декларира за първи път използвайки този идентификатор, при неговото повторно извикване в приложението не е необходимо да се използва знака плюс.
Атрибут android:layout_width and android: layout_height:
Вместо да се използват специфични стойности за работното пространство може да се използва стойността wrap_content, с която се посочва, че елемента трябва да бъде толкова голям, колкото е необходимо, за да се побере неговото съдържание. Ако се използва стойността match_parent, то EditText елемента ще запълни екрана, защото това ще съответства на размера на основната линейна екранна подредба на елементите.
Атрибут Android:hint:
Това е символния низ, който ще се покаже и използва по подразбиране, когато текстовото поле е празно. Вместо да се използва директно символен низ като параметър, стойността @string/edit_message се използва като указател за този низ, който е дефиниран в отделен файл. Тъй като този аргумент се отнася за конкретен ресурс (а не е само идентификатор), то не е необходимо да се използва знака плюс. Въпреки това, тъй като символния низ, към който се извършва обръщението, все още не е дефиниран, при компилиране на програмата ще видите грешка. Този указател за ресурс има същото наименование като идентификатора на елемента – edit_message. Указателите към ресурси винаги използват типа на ресурсите (като идентификатор), така че използването на едно и също наименование не предизвиква грешки при компилиране.
- The attributes in the
Attribute Android:id:
This attribute provides a unique identifier for each object and can be used to retrieve it from the application code. Actions with the object can include reading and manipulating the object, but also a number of other actions. The @ symbol is required when referring to objects in xml files. The data type (in this case id) must be mentioned immediately after this symbol. A slash is placed after the data type, followed by the resource name (edit_message). The plus sign (+) in front of the resource type is only required when a resource identifier is defined for the first time. When compiling the SDK application, the platform will use this identifier to create a new resource record in the gen/R.java file, and this resource will be used as a pointer to the EditText element. Once the resource is declared for the first time using this identifier, it is not necessary to use the plus sign when calling it in the application.
Attributes android:layout_width and android: layout_height:
Instead of using specific features for the specific workspace, the wrap_content value can be used, indicating that the element must be as large as necessary to support its content. If the match_parent value is used, the EditText element will fill the screen because this will correspond to the size of its parent element: LinearLayout.
Attribute Android:hint:
This is the string that will be displayed and used by default when the text box is empty. Instead of using a hardcoded string as a parameter, the value @string/edit_message is used as a pointer to this string, which is defined in an individual file. As this argument applies to a specific resource (not just an identifier), it is not necessary to use a plus sign. However, since the string to which the call is made is not yet defined, you will see an error when compiling the program. The resource pointer has the same name as the element identifier – edit_message. Pointer resources always use the type of resource (as an identifier), so that the same name does not cause compilation errors.

- Стъпка 4. –Дефиниране на символни низове за използване в приложението. По подразбиране, при създаването на демонстрационното приложение за записване и дефиниране на символните низове в проекта ще се използва файла res/values/strings.xml. В този файл може да се дефинират нови стрингове.
Стъпка 5. – Добавяне на символен низ edit_message към проекта. Отворете файла strings.xml, който се намира в папката res/values на работното поле на Android Studio. Добавете нов делител за дефиниране на символен низ и го наименувайте edit_message. Задайте за този символен низ стойност Enter a message. Добавете нов делител за дефиниране на символен низ с наименование button_send и му задайте стойност Send. Този текст ще се използва за бутона, който ще се добави във следващата стъпка. Резултата от действията ви трябва да отговаря на показаното в долната фигура.
- Step 4. – Definition of string variables which will be used in the application. By default, the res/values/strings.xml file will be used to store the string variables in the project. New strings can be defined in this file.
Step 5. – Addition of edit_message string to the project. Open the strings.xml file, which is located in the res/values folder in the Android Studio workspace. Add a new element to define a string and name it edit_message using the name attribute. Set this string to Enter a message between the start and the end tag. Add a new element to define a string named button_send and set it to Send. This text will be used for the button that will be added in the next step. The result of your actions should correspond to what is shown in the figure below.

- Всеки текст, който се визуализира в рамките на приложението е удачно да се дефинира като отделен ресурс в този файл. Дефинирането на стринговете в този начин позволява управлението на всички текстови ресурси посредством един единствен файл. Това прави намирането и обновяването на текстовите ресурси много по-лесно. Извеждането на стринговете в отделен файл позволява и създаването на многоезични приложения, като за съответния език се използва отделен файл с еднакви по дефиниция променливи, но с различно съдържание.
Стъпка 6. – Добавяне на бутон към приложението. От директорията res/layout отворете отново файла activity_main.xml. В рамките на елемента
- Any text that is displayed within the application should be defined as a separate resource in this file. Defining strings in this way allows you to manage all text resources through a single file. This makes finding and updating text resources much easier. Displaying strings in a separate file also allows the creation of multilingual applications, using a separate file for the respective language.
Step 6. – Add a button to the application. From the res/layout directory, open the activity_main.xml file again. Within the

- В рамките на това упражнение бутона няма да бъде дефиниран с идентификатор android:id, какъвто беше използван при дефинирането на текстовото поле. Това се дължи на факта, че реално за бутона няма да има обръщение от програмния код.
Екранната подредба на елементите от графичния интерфейс е реализирана така, че и EditText и Button елементите да заемат толкова пространство, колкото е необходимо за визуализацията на съответния текст, който е дефиниран за тях.
- Within this exercise, the button will not have id attribute (android:id) as the one added to the text box. This is due to the fact that there will actually be no reference to the button in the program code.
The screen arrangement of the elements of the graphical interface is realized so that both EditText and Button elements take up as much space as necessary for the visualization of the respective text, which is defined for them.
- Използването на тези размери за бутона е удачно, но при текстовото поле това може да се укаже проблем, защото потребителя може да въведе текст, който да е по-дълъг от използвания. Адекватното действие в този случай изисква промяна на широчината на текстовото поле. Това може да се извърши посредством модифициране на елемента LinearLayout и промяна на неговия атрибут weight. Този атрибут се използва за указване на пространството, което трябва да се запълни от всеки елемент в екранната подредба (реално указва приоритета/тегловния коефициент на елемента, а не неговата ширина в см или пиксели). Например, ако за определен елемент за този атрибут се зададе стойност 2, а за друг стойност 1, то общата сума от двете стойности е 3 и първия елемент ще заеме 2/3 от оставащото екранно пространство, а втория 1/3. Ако се добави трети елемент и му се зададе стойност 1, тогава първия елемент (с тегловен коефициент 2) ще заеме 1/2 от оставащото пространство на екрана, а останалите ще заемат по 1/4. Стойността по подразбиране за тегловния коефициент за всички елементи е 0, което означава, че ако се определи каквато и да е стойност по-голяма от 0 за определен елемент, но стойността не се промени за другите, то този елемент ще заеме цялото оставащо екранно пространство, след като останалите заемат това, което им е необходимо.
Стъпка 7. – Промяна на полето за въвеждане на текст и разширението му до заемане на целия екран. За да се запълни останалото екранно пространство от използваната екранна подредба с EditText елемента, трябва да се отвори файла activity_my.xml и за елемента
- Using this approach for button sizes is appropriate, but this can be a problem with the text box because the user can enter text that is longer than the one shown in the box. Adequate action in this case requires a change in the width of the text field. This can be done by modifying the LinearLayout element and changing its weight attribute. This attribute is used to specify the space to be filled by each element in the screen layout (actually indicates the priority/weighting of the element, not its width in cm or pixels). For example, if this attribute is set to 2 for one item and 1 to another, the total of the two values is 3, and the first item will take up 2/3 of the remaining screen space and the second 1/3. If a third element is added and set to 1, then the first element (with a weighting factor of 2) will take up 1/2 of the remaining screen space and the rest will take up 1/4. The default value for the weighting factor for all elements is 0, which means that if any value greater than 0 is specified for a certain element, but the value does not change for the others, then this element will occupy all the remaining screen space. , once the others occupy what they need.
Step 7. – Change the text input field and expand it to fill the screen. To fill the remaining screen space of the used screen layout with the EditText element, you must open the activity_main.xml file and set the value of the layout_weight attribute for the

- За да се подобри ефикасността на екранната подредба, когато се промени стойността на тегловния коефициент е удачно и да се промени и стойността за неговата широчина на 0dp. Задаването на тази стойност подобрява производителността на приложението, защото използването на wrap_content като стойност за широчината на елемента изисква системата да изчисли широчината, което в случая е ненужно, защото стойността за тегловния коефициент изисква повторно изчисление на широчината, за да се заеме оставащото място. Фигурата показва резултата от промяната на атрибутите на елемента EditText.
- To improve the efficiency of the screen layout when changing the value of the weighting factor, it is appropriate to change the value for its width to 0dp. Setting this value improves application performance because using wrap_content as the element width value requires the system to calculate the width, which is unnecessary in this case because the weight value requires recalculating the width to take up the remaining space. The figure shows the result of changing the attributes of the EditText element.

- Окончателната версия на activity_main.xml след промяната на атрибутите е показана на следващата фигура
- The final version of activity_main.xml after changing the attributes is shown in the following figure.

- Стъпка 8. – Стартиране и тестване на приложението. След като всички промени до момента са отразени приложението може да се стартира и тества. За целта е необходимо да се използва създадената виртуална машина от предходното упражнение. Ако не сте създали тази виртуална машина следвайте следващите указания. Стартирайте Android Virtual Device (AVD) Manager чрез избор на Tools =>AVD Manager.
- Step 8. – Launch and test the application. Once all changes have been made, the application can be launched and tested. For this purpose it is necessary to use the created virtual machine from the previous exercise. If you did not create this virtual machine, follow these steps. Launch Android Virtual Device (AVD) Manager by selecting Tools=>AVD Manager.

- След това изберете “Create virtual device”. Изберете “Phone” таба и маркирайте Nexus S. Натиснете Next.
- Then select “Create virtual device”. Select the Phone tab and highlight Nexus S. Select Next.

- От следващия екран, отворете “x86 Images”, изберете за версия на ОС => KitKat with API Level => 19 и Target => Android 4.4 (Google APIs). Изберете Next.
- From the screen, open “x86 Images”, select the OS version => KitKat with API Level => 19 and Target => Android 4.4 (Google APIs). Select Next

- Преименувайте устройството по ваш избор. В този случай е кръстено Nexus S API 19. Изберете Finish. Затворете AVD Manager.
- Rename the device as you wish. In this case it is called Nexus S API 19. Select Finish. Close AVD Manager.

- С по-горните стъпки създадохте виртуална машина, която работи с операционна система Android. След това свое действие вече разполагате с всички компоненти за изпълнението на приложението за ОС Android. За тази цел:
- Изберете от менюто Run – > Run ‘app’ (Кратки клавиши – Shift+F10). След компилиране на програмния код Android Studio ще стартира емулатора и ще визуализира приложението.
- Щом емулатора стартира и зареди операционната система приложението ви ще се стартира само. Можете да си взаимодействате с виртуалната машина използвайки мишката. Разгледайте функционалността на виртуалния смартфон.
Стартирането на емулатора може да отнеме няколко минути на по-слаби машини!
- With the above steps, you have created virtual machine that runs the Android operating system. After this action, you now have all the components to run the Android application. For this purpose:
- Choose from the menu Run -> Run ‘app’ (Shortcuts – Shift + F10). After compiling the program code, Android Studio will start the emulator and display the application.
- Once the emulator starts and loads the operating system, your application will start automatically. You can interact with the virtual machine using the mouse. Take a look at the functionality of the virtual smartphone.
The boot time of the virtual machine can take a couple of minutes on computers with low resources!

4. Добавяне на функционалност към приложението и дефиниране на допълнителен екран за извеждане на съобщение
- Стъпка 1. – Дефиниране на действие при натискане на бутона. От папката res/layout изберете отново файла activity_main.xml. Към елемента <Button> добавете атрибута android:onClick.
- Step 1. – Defining an action on the click of a button. From the res/layout folder, select the activity_main.xml file again. Add the android: onClick attribute to the <Button> element.

- Атрибута android:onClick трябва да приеме стойност “sendMessage”. Тази стойност носи наименованието на метода, който ще се извика от системата при натискане на бутона. От папката java/com.example.lab2 изберете файла MainActivity.java. В рамките на класа MainActivity добавете празния (за сега) метод sendMessage().
- The android:onClick attribute must take the value “sendMessage”. This value is the name of the method that will be called by the system when the button is pressed. From the java/com.example.lab2 folder, select the MainActivity.java file. Within the MainActivity class, add the empty (for now) sendMessage () method.

- За да може системата да свърже този метод с метода, който се извиква от атрибута android:onClick, дефиницията трябва да отговаря на следните особености:
- Трябва да е публична public
- Трябва да се дефинира с стойност void, т.е. да не връща стойност
- Трябва да разполага с един единствен параметър – View
Стъпка 2. – Дефиниране на intent елемент за реакция при натискането на бутона. От файла MainActivity.java изберете метода sendMessage() и създайте нов intent елемент за стартиране на работен екран с наименование DisplayMessageActivity (все още не сме го създали). Програмния код за това е следния:
- In order for the system to associate this method with the method called by the android:onClick attribute, the definition of the method must meet the following rules:
- Must be public
- Must be defined with a void value, that is to not return value
- Must have a single parameter – View
Step 2. – Define an intent element for response at the touch of a button. From the MainActivity.java file, select the sendMessage () method and create a new intent item to launch a new work screen named DisplayMessageActivity (we haven’t created it yet). The program code for this is as follows:

Обръщението към DisplayMessageActivity ще предизвика извеждане на грешка, поради факта, че този обект все още не съществува. За сега игнорирайте тази грешка!
- Синтаксиса за дефиниране на intent елемента изисква използването на два параметъра:
- Параметъра Context е първия атрибут (използва се защото текущия клас e подклас на Context);
- Параметър за указване на класа, който ще поеме обработката на подаваната информация (в този случай това е новия работен екран)
Android Studio ще ви укаже, че трябва да импортирате класа Intent за работа с intent елементи. Най-отгоре във файла импортирайте класа Intent:
Calling DisplayMessageActivity will result to an error because this object doesn’t exist yet. Ignore this error for now!
- The syntax for defining the intent element requires the use of two parameters:
- The Context parameter is the first attribute (used because the current class is a subclass of Context);
- Parameter for specifying the class that will take over the processing of the submitted information (in this case this is the new work screen)
Android Studio will tell you that you need to import the Intent class to work with intent elements. At the top of the file, import the Intent class:

- Използвайте Alt + Enter (option + return за Mac), за да добавите автоматично всички липсващи класове. В метода sendMessage() използвайте функцията findViewById(), за да укажете EditText елемента.
- Use Alt + Enter (option + return for Mac) to automatically add all missing classes. In the sendMessage() method, use the findViewById() function to specify the EditText element.

- Най-отгоре на файла импортирайте липсващия EditText клас. Дефинирайте текста да се записва в локална променлива и използвайте метода putExtra() за добавяне на съобщението към intent елемента.
- At the top of the file, import the missing EditText class. Define the text to be stored to a local variable and use the putExtra () method to add the message to the intent element.

- Всеки intent елемент може да предава различен тип информация посредством двойки ключ-стойност, които се наричат екстри (extras). Метода putExtra() приема за първи параметър стойността за ключа (уникален идентификатор), а за втори параметър стойността на променливата. Най-отгоре на класа MainActivity добавете дефиницията за локалната променлива EXTRA_MESSAGE.
- Each intent element can transmit a different type of information through key-value pairs, which are called extras. The putExtra () method takes the key value (unique identifier) as the first parameter, and the value of the variable as the second parameter. At the top of the MainActivity class, add the definition for the local variable EXTRA_MESSAGE.

- За да може работния екран за визуализация на съобщението да изиска данните записани от екстрата е необходимо да се дефинира стойността за ключа в intent елемента. За тази цел се използва константа с публичен достъп. Добра практика е ключовете да се дефинират посредством наименованието на приложението като префикс. Това гарантира уникалността на ключовете в случаите, когато локалното приложението комуникира с други приложения. За метода sendMessage() дефинирайте обръщение към startActivity() метода, като укажете извикването и визуализацията на създадения intent елемент. С добавянето на този нов код sendMessage() трябва да придобие следния вид:
- In order for the working screen which will visualize the message to request the data saved from the extra, it is necessary to define the value for the key in the intent element. A public constant is used for this purpose. It is good practice to define keys using the application name as a prefix. This ensures the uniqueness of the keys in cases where the local application communicates with other applications. For the sendMessage() method, define a reference to the startActivity() method, specifying the invocation and visualization of the created intent element. By adding this new code sendMessage() should take the following form.

- При изпълнение на този код системата ще стартира указания от intent елемента работен екран. Ако се опитате да стартирате приложението към този момент от време ще ви се изведе грешка – това се дължи на факта, че реално все още не е създаден допълнителния екран DisplayMessageActivity, който ще се използва за визуализация на съобщението.
5. Създаване на нов работен екран, прихващане и визуализация на съобщението
- Стъпка 1. – Създаване на нов работен екран за визуализация на въведеното съобщение. По подразбиране Android Studio добавя onCreate() при създаването на нов работен екран. От основния екран на Android Studio изберете директорията java и разгърнете пакета com.example.lab2, изберете пакета с десен бутон на мишката и изберете New> Activity> Empty Activity.
- When executing this code, the system will start the work screen specified by the intent element. If you try to start the application at this point in time you will get an error – this is due to the fact that the additional screen DisplayMessageActivity has not yet been created, which will be used to visualize the message.
5. Create a new work screen, capture and visualize the message
- Step 1. – Create a new work screen to visualize the entered message. By default, Android Studio adds onCreate() when creating a new work screen. From the main screen of Android Studio, select the java directory and expand the package com.example.lab2, select the package with the right mouse button and select New> Activity> Empty Activity.

- Ще ви се появи познатия вече екран за дефиниране на основните параметри за работния екран. Дефинирайте следните стойности:
- Activity Name: DisplayMessageActivity
- Layout Name: activity_display_message
- Package name: com.example.lab2
- The familiar screen for defining the basic parameters for the work screen will appear. Define the following values:
- Activity Name: DisplayMessageActivity
- Layout Name: activity_display_message
- Package name: com.example.lab2

- Изберете Finish. Отворете файла DisplayMessageActivity.java, който ще се създаде с последното ви действие. В него вече е дефиниран метода onCreate(), който ще разширим по-късно. Ако искате стартирайте приложението в симулатор. Към текущия момент не би трябвало да ви се изведът никакви грешки, но и приложението няма да извършва никакви действия – натискането на бутона Send ще стартира втория работен екран, но той е празен по подразбиране, а няма да изведе въведения в текстовото поле текст.
Стъпка 2. – Получаване на данните от intent елемента. Всеки работен екран се извиква с помощта на intent елемент, независимо от метода за достигане на потребителя до него. Чрез извикване на метода getIntent() можете да стартирате новия работен екран и да получите данните, които се съхраняват в intent елемента. Към файла DisplayMessageActivity.java в дефиницията на метода onCreate() премахнете следния ред:
- Select Finish. Open the DisplayMessageActivity.java file that will be created by your last action. It already defines the onCreate() method, which we will expand later. If you want, run the application in a simulator. At the moment you should not see any errors, but the application will not take any action – pressing the Send button will start the second screen, but it will display empty screen by default, not the message you entered in the text box.
Step 2. – Get the data from the intent element. Each work screen is called using an intent element, regardless of the method the user reaches it. By calling the getIntent () method, you can start the new work screen and retrieve the data stored in the intent element. In the DisplayMessageActivity.java file in the onCreate () method definition, remove the following line.

- Извикайте intent елемента и го задайте като стойност за локална променлива:
Intent intent = getIntent();
Най-отгоре на файла добавете класа Intent и използвайте Alt + Enter, за да добавите другите липсващи класове. Използвайте метода getStringExtra() за извикване на съобщението от импортирания intent елемент.
- Call the intent element and set it as a value for a local variable:
Intent intent = getIntent ();
Add the Intent class at the top of the file and use Alt + Enter to add the other missing classes. Use the getStringExtra() method to call the message from the imported intent element.

- Стъпка 3. – Визуализация на съобщението. За метода onCreate() създайте нов TextView обект с командата.
TextView textView = new TextView(this);
Използвайте setText(), за да укажете съобщението и неговата големина.
textView.setTextSize(40);
textView.setText(message);
Добавете TextView елемента като основен за екранната подредба, чрез извикването му посредством метода setContentView().
setContentView(textView);
Най-отгоре на файла импортирайте TextView класа и използвайте Alt + Enter, за да добавите всички липсващи класове. Метода onCreate() в завършен вид е представен на фигурата.
- Step 3. – Visualization of the message. For the onCreate() method, create a new TextView object with the command.
TextView textView = new TextView(this);
Use setText() to specify the message and its size.
textView.setTextSize(40);
textView.setText(message);
Add the TextView element as the default for the screen layout by calling it using the setContentView() method.
setContentView(textView);
At the top of the file, import the TextView class and use Alt + Enter to add all the missing classes. The onCreate() method in its finished form is shown in the figure.

- Стъпка 4. – Стартиране на приложението и преглед на неговата функционалност. С изпълнението на горните действия вие завършихте създаването на това приложение. Стартирайте го в симулатора и проверете неговата функционалност. След въвеждане на текстово съобщение в полето за въвеждане и натискане на бутона Send, въведеното съобщение трябва да се изведе на нов работен екран!
- Step 4. – Launch the application and review its functionality. By completing the above steps, you have completed the creation of this application. Run it in the simulator and check its functionality. After entering a text message in the input field and pressing the Send button, the entered message must be displayed on a new work screen!

Вие успешно приключихте това упражнение и създадохте и тествахте своето първо приложение с графичен интерфейс за Android ОС!
You have successfully completed this exercise and created and tested your first GUI application for Android OS!
