Работа с екранни подредби (Layouts). Реализиране на приложение с две екранни подредби, които се използват в зависимост от ориентацията на устройството. / Working with screen layouts. Implementation of the application with two screen layouts, which are used depending on the orientation of the face.
1. Въведение
- Екранната подредба определя визуалната структура на потребителския интерфейс за всеки работен екран или за всяко пособие (widget). Декларирането на екранна подредба може да се осъществи по два начина:
- Деклариране на UI елементите в XML – Android средата за разработване на приложения предоставя възможност за използване на XML синтаксис за дефиниране на различни View класове и подкласове, които да се използват за създаване на елементите на графичния интерфейс.
- Деклариране на елементи чрез графичен редактор – позволява се създаването и конфигурирането на различни елементи посредством графичен редактор и използване на елементи или обекти за всеки от компонентите на графичния интерфейс на приложението.
Платформата за разработване на приложения за Android ви позволява да използвате всеки от тези методи по отделно или и двата метода заедно. Например – можете да използвате графичния редактор, за да създадете и позиционирате елементите (бутони, текстови полета, изображения и т.н.), а след това да използвате съответните .xml файлове, за да зададете или промените действието на отделните елементи.
Предимството на декларирането на UI елементите в XML се изразява в това, че се предоставя възможност за разделяне на процеса по създаване на приложението на две плоскости – една, която се занимава с графичното оформление на приложението и една, която се занимава с неговата функционалност. По този начин описанието на UI елементите се явява като външен елемент за основния код на приложението, което означава, че можете да променяте визията на елементите и тяхната подредба без да се налага да прекомпилирате цялото приложение. Това ви позволява да създадете XML екранни подредби за различните възможни ориентации на екрана, за устройства с различни размери на екрана и за приложения, които се използват на различни езици. Допълнително, дефинирането на екранната подредба в XML позволява по-лесното визуализиране на приложението и съответното отстраняване на грешки. В рамките на това практическо упражнение ще разгледаме именно това, как се дефинират различните екранни подредби в XML.
Като цяло, XML синтаксиса за деклариране на елементи от потребителския интерфейс следва приетите структура и начини за именуване на класовете и методите, като имената на елементите съответстват на имената на класовете, а имената на атрибутите съответстват на методите.
- The screen layout determines the visual structure of the user interface for each work screen or for each widget. Declaring a screen layout can be done in two ways:
- Declaring UI elements in XML – The Android application development environment provides the ability to use XML syntax to define various View classes and subclasses which could be used to create GUI elements.
- Declaring elements using a graphic interface – allows the creation and configuration of various elements through a graphic interface and the use of elements or objects for each of the components of the graphical interface of the application.
The Android application development platform allows you to use each of these methods separately or both methods together. For example, you can use the graphic editor to create and position the items (buttons, text boxes, images, etc.), and then use the appropriate .xml files to set or change the action of individual items.
The advantage of declaring UI elements in XML is that it provides the ability to divide the application creation process into two parts – one that deals with the graphical layout of the application and one that deals with its functionality. In this way, the description of the UI elements appears as an external element to the main code of the application, which means that you can change the appearance of the elements and their arrangement without having to recompile the entire application. This allows you to create XML screen layouts for different possible screen orientations, for devices with different screen sizes, and for applications that are used in different languages. Additionally, defining the screen layout in XML makes it easier to visualize the application and debug accordingly. In this practical exercise, we will look at exactly how different screen layouts are defined in XML.
In general, the XML syntax for declaring UI elements follows the accepted structure and convention of naming classes and methods, with element names corresponding to class names and attribute names corresponding to methods.
- Създаване и преглед на ново приложение в зависимост от ориентацията на устройството;
- Създаване на екранни подредби за вертикална и хоризонтална ориентация на устройството;
- Дефиниране на елементи и компоненти за двете екранни подредби;
- Преглед на приложението посредством симулатор на смартфон.
3. Създаване на ново приложение в зависимост от ориентацията на устройството
- Стъпка 1. – Създаването на ново приложение може да стане по познатия начин от предходното упражнение. От началният екран на Android Studio (ако Android Studio директно отвори последния проект, трябва да го затворите за да стигнете до началния екран), изберете “New project”. На следващия екран, изберете “Empty Activity”.
- Create and view a new application depending on the orientation of the device;
- Creating screen layouts for vertical and horizontal orientation of the device;
- Defining elements and components for the two screen layouts;
- View the application using a smartphone simulator.
3. Creating 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: Lab3
- Package name: com.example.lab3
- Save location: C:\Users\your_username\AndroidStudioProjects\Lab3
- Language: Java
- Minimum SDK: API 19: Android 4.4 (KitKat)
След което натиснете Finish. ще генерира автоматично всички файлове и компоненти, от които ще се състои новото приложение. След приключване на този процес ще се изведе следния прозорец:
- On the next screen, enter the following project settings and select Next:
- Name: Lab3
- Package name: com.example.lab3
- Save location: C:\Users\your_username\AndroidStudioProjects\Lab3
- 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
- Стъпка 3. – Преглед на приложението при хоризонтална и вертикална ориентация на виртуалния смартфон. След зареждане на виртуалното устройство и стартиране на приложението използвайте клавишната комбинация Ctrl+F11, за да завъртите екрана на емулатора и да предизвикате смяна на ориентацията на смартфона.
- 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
- Step 3. – View the application in horizontal and vertical orientation of the virtual smartphone. After loading the virtual device and starting the application, use the key combination Ctrl + F11 to rotate the emulator screen and cause the change of the smartphone’s orientation.

4. Създаване на екранни подредби за вертикална и хоризонтална ориентация на устройството
- Стъпка 1 -Създаване на нови екранни подредби за вертикална и хоризонтална ориентация на устройството. Използвайте файлов браузър и достъпете папката с проекта, която трябва да се намира в папката C:\Users\your_username\AndroidStudioProjects, ако сте инсталирали Android Studio с настройки по подразбиране. В папката с проекта се намират няколко папки, които съхраняват ресурсите за приложението – .gradle, .idea, app и т.н. Преминете към папката с ресурсите за проекта – app\src\main\res.
- Step 1 – Create new screen layouts for vertical and horizontal orientation of the device. Use a file browser and access the project folder, which should be located in the C:\Users\your_username\AndroidStudioProjects if you have installed Android Studio with default settings. In the project folder there are several folders that store the resources for the application – .gradle, .idea, app, etc. Navigate to the project resources folder – app\src\main\res.

- Както виждате от фигурата, тази папка съдържа редица подпапки. В папката drawable се съхраняват графичните файлове за приложението, в папка values се съхраняват файловете с променливите за приложението (включително strings.xml), в папките mipmap се съхраняват иконите за приложението, които се използват за различните видове устройства и при различна резолюция на екрана. Към текущия момент от време, от съдържанието на папка res ни интересува единствено и само папка layout. Тя съдържа в себе си файла activity_main.xml, който се използва за дефиниране на различните елементи от екранната подредба.
Копирайте тази папка и преименувайте копието на layout-land. Преименувайте оригиналната папка на layout-port. По този начин вместо една папка с наименование layout трябва да имате две. В тези две папки се съдържат файловете, които ще определят екранната подредба при поставяне на устройството в хоризонтално и вертикално положение.
Върнете се обратно в работната среда на Android Studio. Използвайте клавишната комбинация Ctrl+Alt+Y, за да обновите работната среда. В лявата работна лента за layout трябва да се появят два файла – activity_main.xml (land) и activity_main.xml (port).
- As you can see from the figure, this folder contains a number of subfolders. The drawable folder stores application graphic files, the values folder stores application variable files (including strings.xml), and the mipmap folders store application icons that are used for different types of devices and for different screen resolutions. At the moment, from the content of the res folder we are only interested in the layout folder. It contains the activity_main.xml file, which is used to define the various elements of the screen layout.
Copy this folder and rename the copy to layout-land. Rename the original to layout-port folder. That way, instead of one folder named layout, you should have two. These two folders contain the files that will determine the screen layout when placing the device horizontally and vertically.
Go back to the Android Studio workspace. Use Ctrl + Alt + Y to refresh the workspace. Two files should appear in the left layout taskbar – activity_main.xml (land) and activity_main.xml (port).

5. Дефиниране и създаване на елементи за вертикалната екранна подредба
- Стъпка 1. – Заменете съдържанието на файла activity_main.xml (port) със следния код:
Step 1. – Replace the content of activity_main.xml (port) with the following code:

- В това упражнение ще се използва RelativeLayout. За да се тестват двете екранни подредби за всяка трябва да се създадат по два елемента от тип TextView, един елемент от тип ImageView и един елемент от тип ScrollView, който ще съдържа основния текст. За целта първо трябва да се предефинират атрибутите на екранната подредба.
Стъпка 2. – Добавете нов елемент от тип TextView, който ще използваме за визуализация на заглавието на този екран. Задайте за този елемент централно подравняване на екрана с атрибута layout_centerHorizontal=”true”, отстъп от горната страна на екрана от 8dp с атрибута layout_marginTop=”8dp” и големина на символите от 22 с атрибута textSize=”22sp”. Текста, който трябва да се визуализира от този елемент ще се съхранява в променливата TBL.
- RelativeLayout will be used in this exercise. To test the two screen layouts, two TextView elements, one ImageView element, and one ScrollView element, which will contain the main text must be created for each layout.
Step 2. – Add a new TextView element, which we will be used to display the title on this screen. Set this item to a central screen alignment with the layout_centerHorizontal = “true” attribute, an 8dp indent at the top of the screen with the layout_marginTop = “8dp” attribute, and a 22 character size with the textSize = “22sp” attribute. The text to be visualized by this element will be stored in the TBL variable.

- Стъпка 3. – Добавете нов елемент от тип ImageView. Елементите от този тип служат за визуализация на изображения. Подобно на TextView елементите и за този тип елементи трябва да се използват атрибути за определяне на отстъпите, централното или страничното подравняване, местоположението спрямо другите елементи в екранната подредба и т.н.
Задайте за този елемент отстъп от горния елемент от 8dp с атрибута paddingTop=”8dp”, да не е подравнен в центъра на екранна с атрибута layout_centerHorizontal=”false”, да се намира след елемента за визуализация на текст, който дефинирахме в предишната стъпка, с атрибута layout_below=”@id/textView1″ и да позволява мащабиране на изображението с атрибута scaleType=”fitXY”. Допълнително всички изображения, които се визуализират поддържат и възможността при задържане на пръст върху тях да извеждат описателен текст. За да позволите тази функционалност използвайте атрибута contentDescription=”@string/TBL”, с който ще изведете текста записан в променливата TBL. Подобно на TextView елементите, които използват указатели към променливите дефинирани във файла strings.xml и ImageView елементите използват указатели за извикване на изображения, които се намират в папка drawable на проекта. В този случай с добавянето на атрибута src=”@drawable/tbl” ще се визуализира изображението tbl.jpg.
- Step 3. – Add a new element of type ImageView. Elements of this type are used for visualization of images. Like TextView elements, this type of element must use attributes to specify indents, center or side alignment, position relative to other elements in the screen layout, and so on.
Set this element indent from the top to 8dp with the paddingTop = “8dp” attribute, not aligned in the center of the screen with the layout_centerHorizontal=”false” attribute, after the text element we defined in the previous step, with the layout_below =”@id/textView1″ attribute and allow scaling the image with the scaleType=”fitXY” attribute. Additionally, all images that are displayed support the ability to display descriptive text when you hold your finger on them. To enable this functionality, use the contentDescription=”@string/TBL” attribute, which will display the text stored in the TBL variable. Like TextView elements, which use pointers to the variables defined in the strings.xml file, ImageView elements use pointers to call up images that are in the project’s drawable folder. In this case, adding the src=”@drawable/tbl” attribute will display the tbl.jpg image.

- Стъпка 4. – Дефинирането на втория TextView елемент изисква предварителното дефиниране на ScrollView елемент. Чрез този елемент се позволява визуализирането на елементи, които не биха могли да се визуализират в рамките на един работен екран на устройството. Дефинирайте елемента така, че да е под заглавието с атрибута layout_below=”@id/textView1″ и отдясно на изображението с атрибута layout_toRightOf=”@id/imageView1″ и задайте отстъп отгоре и отляво равен на 8dp.
- Step 4. – Defining the second TextView element requires pre-defining a ScrollView element. This item allows the display of items that could not be displayed within a single work screen of the device. Define the element so that it is below the title with the layout_below=”@id/textView1″ attribute and to the right of the image with the layout_toRightOf=”@id/imageView1″ attribute, and set the top and left indents to 8dp.

- Стъпка 5. – Дефинирайте втория TextView елемент. Задайте за елемента отстъп отгоре от 8dp с атрибута layout_marginTop=”8dp” и големина на символите от 22 с атрибута textSize=”22sp”. Текста, който трябва да се визуализира от този елемент ще се съхранява в променливата TBLText.
- Step 5. – Define the second TextView element. Set the top indent to 8dp with the layout_marginTop=”8dp” attribute and the 22 character size with the textSize=”22sp” attribute. The text to be visualized by this element will be stored in the TBLText variable.

- Пълното съдържание на файла за екранната подредба е представено на следващата фигура.
- The full content of the file of this layout is presented in the next figure.

6. Дефиниране и създаване на елементи за хоризонталната екранна подредба
- Стъпка 1. – След създаването на вертикалната екранна подредба е необходимо да се повтори процеса и за хоризонталната екранна подредба. Изберете файла activity_main.xml (land) и го заредете в основния екран на Android Studio. Заменете съдържание на файла със следния код:
- Step 1. – After creating the vertical screen layout, it is necessary to repeat the process for the horizontal screen layout. Select the activity_main.xml (land) file and load it on the Android Studio main screen. Replace the content of the file with the following code:

- Аналогично на файла за вертикална екранна подредба и този файл трябва да се промени, като се добавят два елемента от тип TextView, един елемент от тип ImageView и един елемент от тип ScrollView, който да съдържа основния текст.
Дефинирайте първия TextView елемент, така че да е подравнен централно на екрана, да е на 8dp отстояние от горния ръб на работното пространство и да позволява визуализация на текста с големина на символите от 22sp. Променливата, която трябва да съдържа текста за този е TBL.
Втория елемент на екранната подредба отново ще е изображение. Дефинирайте ImageView елемента с 8dp отстояние от горния елемент и укажете този път изображението да е центрирано в средата на екрана. Изображението трябва да е под заглавието на страницата и да се мащабира (scaleType=”fitXY”). ImageView елемента трябва да визуализира изображението tbl.jpg и да има за описателен текст съдържанието на променливата TBL.
След изображението, на екрана трябва да се изведе и основния текст. За целта трябва да се добави ScrollView елемент, който да е с големина и широчина равна на екранната подредба (layout_width=”match_parent” и layout_height=”match_parent”) и трябва да се намира под изображението.
В ScrollView елемента дефинирайте нов TextView елемент и му задайте да е с 8dp отстояние отгоре и да визуализира текста с големина на символите от 22sp. Съдържанието на този елемент трябва да се зарежда посредством указател към променливата TBLText.
Пълното съдържание на файла за екранната подредба е представено на следващата фигура.
- Similar to the vertical screen layout file, this file must be modified by adding two TextView elements, one ImageView element and one ScrollView element containing the main text.
Define the first TextView element so that it is centered on the screen, 8dp away from the top edge of the screen, and text size to be displayed at 22sp. The variable that must contain the text for this is TBL.
The second element of the screen layout will be an image. Define the ImageView element with a distance of 8dp from the above element and this time specify that the image is centered in the middle of the screen. The image must be below the page title and scaled (scaleType=”fitXY”). The ImageView element must visualize the image tbl.jpg and have the content of the variable TBL as descriptive text.
After the image, the main text should be displayed on the screen. To do this, you must add a ScrollView element that is the same size and width as the screen layout (layout_width=”match_parent” and layout_height=”match_parent”) and must be located below the image.
In the ScrollView element, define a new TextView element and set it to be 8dp apart from the top and display text with a 22sp character size. The content of this element must be loaded using a pointer to the TBLText variable.
The complete content of the screen layout file is presented in the next figure.

7. Създаване на ресурсите и тестване на приложението
- Стъпка 1. – След като сте дефинирали елементите за двете екранни подредби, можете да забележите, че ресурсите, които са необходими за тяхната визуализация са оцветени в червено. Това е така, защото тези ресурси не са създадени все още.
Заредете файла strings.xml от папката values. Съдържанието му трябва да отговаря на това от фигурата.
- Step 1. – Once you have defined the elements for the two screen layouts, you may notice that the resources needed to visualize the text and the images are highlighted in red. This is because these resources have not been created yet.
Load the strings.xml file from the values folder. Its content must correspond to that of the figure.

- Добавете двете текстови променливи, които дефинирахте в екранните подредби – TBL и TBLText.
<string name=”TBL”>Sir Timothy John Berners-Lee</string>
<string name=”TBLText”> Sir Timothy John <Tim> Berners-Lee (born 8 June 1955), also known as (TimBL) is a British computer scientist, best known as the inventor of the World Wide Web. He made a proposal for an information management system in March 1989, and he implemented the first successful communication between a Hypertext Transfer Protocol (HTTP) client and server via the Internet sometime around mid-November. Berners-Lee is the director of the World Wide Web Consortium (W3C), which oversees the Webs continued development. He is also the founder of the World Wide Web Foundation, and is a senior researcher and holder of the Founders Chair at the MIT Computer Science and Artificial Intelligence Laboratory (CSAIL). He is a director of the Web Science Research Initiative (WSRI), and a member of the advisory board of the MIT Center for Collective Intelligence. In 2004, Berners-Lee was knighted by Queen Elizabeth II for his pioneering work. In April 2009, he was elected a foreign associate of the United States National Academy of Sciences. He was honoured as the /Inventor of the World Wide Web/ during the 2012 Summer Olympics opening ceremony, in which he appeared in person, working with a vintage NeXT Computer at the London Olympic Stadium. He tweeted /This is for everyone/, which was instantly spelled out in LCD lights attached to the chairs of the 80,000 people in the audience. </string>
Изтеглете изображение на Сър Тим Бърнърс-Лий от следния линк:
https://imgur.com/z4yL6AJ и го запазете като tbl.jpg в папката с изображения за приложението:
C:\Users\your_username\AndroidStudioProjects\Lab3\app\src\main..
..\res\drawable
Стъпка 2. – Прегледайте как ще се визуализира приложението в работната среда (Preview). Компилирайте и стартирайте проекта с клавишната комбинация Shift+F10. Както можете да видите на фигурата, приложението се визуализира съгласно двете екранни подредби, които дефинирахте. Анализирайте ScrollView елементите. Каква функционалност ви предоставят те? Пробвайте да ги премахнете и стартирайте повторно приложението. Каква е функционалността сега?
- Add the two text variables that you defined in the screen layouts, TBL and TBLText.
<string name=”TBL”>Sir Timothy John Berners-Lee</string>
<string name=”TBLText”> Sir Timothy John <Tim> Berners-Lee (born 8 June 1955), also known as (TimBL) is a British computer scientist, best known as the inventor of the World Wide Web. He made a proposal for an information management system in March 1989, and he implemented the first successful communication between a Hypertext Transfer Protocol (HTTP) client and server via the Internet sometime around mid-November. Berners-Lee is the director of the World Wide Web Consortium (W3C), which oversees the Webs continued development. He is also the founder of the World Wide Web Foundation, and is a senior researcher and holder of the Founders Chair at the MIT Computer Science and Artificial Intelligence Laboratory (CSAIL). He is a director of the Web Science Research Initiative (WSRI), and a member of the advisory board of the MIT Center for Collective Intelligence. In 2004, Berners-Lee was knighted by Queen Elizabeth II for his pioneering work. In April 2009, he was elected a foreign associate of the United States National Academy of Sciences. He was honoured as the /Inventor of the World Wide Web/ during the 2012 Summer Olympics opening ceremony, in which he appeared in person, working with a vintage NeXT Computer at the London Olympic Stadium. He tweeted /This is for everyone/, which was instantly spelled out in LCD lights attached to the chairs of the 80,000 people in the audience. </string>
Download an image of Sir Tim Berners-Lee from the following link:
https://imgur.com/z4yL6AJ and save it as tbl.jpg in the image folder for the app:
C:\Users\your_username\AndroidStudioProjects\Lab3\app\src\main..
..\res\drawable
Step 2. – Preview how the application will be displayed in the work environment (Preview). Compile and start the project with the key combination Shift + F10. As you can see in the figure, the application is displayed according to the two screen layouts that you have defined. Analyze ScrollView items. What functionality do they provide you? Try removing them and restarting the application. What is the functionality now?

- Стъпка 3. – За да се демонстрира истинската сила на екранните подредби, те ще се променят така, че при вертикална позиция на устройството ще се извежда една информация, а при хоризонтална позиция друга. За целта дефинирайте във файла strings.xml още две променливи – JA и JAText. Съдържанието им трябва да е следното.
<string name=”JA”>John Atanasoff</string>
<string name=”JAText”> John Vincent Atanasoff (October 4, 1903 – June 15, 1995) was an American physicist and inventor, best known for inventing the first electronic digital computer. Atanasoff invented the first electronic digital computer in the 1930s at Iowa State College. Challenges to his claim were resolved in 1973 when the Honeywell v. Sperry Rand lawsuit ruled that Atanasoff was the inventor of the computer. His special-purpose machine has come to be called the Atanasoff–Berry Computer. </string>
Изтеглете изображение на Джон Атанасов от следния линк:
https://imgur.com/PyW6g66 и го запазете като ja.jpg в папката с изображения за приложението:
C:\Users\your_username\AndroidStudioProjects\Lab3\app\src\main..
..\res\drawable
Променете хоризонталната екранна подредба така, че да използва JA, JAText и ja вместо съответстващите им файлове и променливи за Сър Тим Бърнърс-Лий. Стартирайте повторно приложението и завъртете виртуалното устройство. Какъв е ефекта? След промените хоризонталната и вертикалната екранна подредба трябва да се различават значително
- Step 3. – To demonstrate the true power of the screen layouts, they will be changed so that one information will be displayed in the vertical position of the device and another in the horizontal position. To do this, two more variables should be defined in the strings.xml file – JA and JAText. Their content should be as follows.
<string name=”JA”>John Atanasoff</string>
<string name=”JAText”> John Vincent Atanasoff (October 4, 1903 – June 15, 1995) was an American physicist and inventor, best known for inventing the first electronic digital computer. Atanasoff invented the first electronic digital computer in the 1930s at Iowa State College. Challenges to his claim were resolved in 1973 when the Honeywell v. Sperry Rand lawsuit ruled that Atanasoff was the inventor of the computer. His special-purpose machine has come to be called the Atanasoff–Berry Computer. </string>
Download an image of John Atanasoff from the following link:
https://imgur.com/PyW6g66 and save it as ja.jpg in the image folder for the app:
C:\Users\your_username\AndroidStudioProjects\Lab3\app\src\main..
..\res\drawable
Change the horizontal screen layout to use JA, JAText, and ja instead of their corresponding Sir Tim Berners-Lee files and variables. Restart the application and rotate the virtual device. What is the effect? After the changes, the horizontal and vertical screen arrangements must differ significantly.

Вие успешно приключихте това упражнение и създадохте две екранни подредби за работа с мобилно устройство при вертикално и хоризонтално позициониране!
You have successfully completed this exercise and created two screen layouts for working with a mobile device in vertical and horizontal orientation!
