Framelayout android для чего используется

FrameLayout

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

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

Также можно использовать свойства Gravity для управления порядком размещения.

FrameLayout можно использовать для интересного эффекта, когда верхняя часть (TextView) остаётся неизменной, а основной контент прокручивается.

Поочередная смена картинки

Создадим разметку, когда на экран динамически выводится только одно изображение.

Теперь код для активности, где при нажатии на изображении, оно будет заменяться на другое.

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

Имейте в виду, что размер компоновки FrameLayout определяется наибольшим элементом в контейнере. Поэтому более маленькое изображение может растянуться.

Если часть элементов сверху стопки являются невидимыми, то могут наблюдаться проблемы с выводом на экран. В этих случаях рекомендуется вызывать метод setMeasureAllChildren() с аргументом true (аналог метода — атрибут android:measureAllChildren=»true»).

Источник

Основы верстки для нативных андроид приложений

( пользоваться не рекомендуется, deprecated )
AbsoluteLayout — означает что каждый элемент верстки будет иметь абсолютную позицию относительно верхнего левого угла экрана задаваемую с помощью координат x и y. Т.е. верхнийлевый угол экрана при AbsoluteLayout имеет координаты x = 0, y = 0.
Позиция указывается в атрибутах элемента android:layout_x и android:layout_y.
Пример кода:

FrameLayout

FrameLayout — тип верстки внутри которого может отображаться только один элемент в строке. Т.е. если внутри FrameLayout вы поместите несколько элементов, то следующий будет отображаться поверх предыдущего.
Пример кода:

LinearLayout

LinearLayout — тип верстки при котором область верстки делится на строки и в каждую строку помещается один элемент. Разбиение может быть вертикальное или горизонтальное, тип разбиения указывается в атрибуте LinearLayout android:orientation. Внутри верстки возможно комбинировать вертикальную и горизонтальную разбивки, а кроме того, возможна комбинация нескольких разных типов верстки например использование LinearLayout внутри FrameLayout.

Пример вертикальной разбивки LinearLayout:

Пример горизонтальной разбивки LinearLayout:

Комбинация нескольких LinearLayout:

RelativeLayout

RelativeLayout — тип верстки при котором позиционирование элементов происходит относительно друг друга и относительно главного контейнера.
За то, каким образом будут позиционироваться элементы отвечают следующие атрибуты:
Атрибуты позиционирования относительно контейнера

  • android:layout_alignParentBottom – Низ элемента находится внизу контейнера
  • android:layout_alignParentLeft – Левая часть элемента прилегает к левой части контейнера
  • android:layout_alignParentRight – Правая часть элемента прилегает к правой части контейнера
  • android:layout_alignParentTop – Элемент находится в верхней части контейнера
  • android:layout_centerHorizontal – Элемент позиционируется по центру относительно горизонтального размера контейнера
  • android:layout_centerInParent – Элемент позиционируется по центру относительно горизонтального и вертикального размеров размера контейнера
  • android:layout_centerVertical – Элемент позиционируется по центру относительно вертикального размера контейнера
Читайте также:  Проверка системных ошибок андроид

Атрибуты позиционирования относительно других элементов.
В качестве значений этих атрибутов ставятся id элемента относительно которого будет производится позиционирование.

android:layout_above – Распологает элемент над указанным
android:layout_below – Распологает элемент под указанным
android:layout_toLeftOf – Распологает элемент слева от указанного
android:layout_toRightOf – Распологает элемент справа от указанного

Выравнивание относительно других элементов.

android:layout_alignBaseline – Выравнивает baseline элемента с baseline указаннго элемента
android:layout_alignBottom – Выравнивает низ элемента по низу указанного элемента
android:layout_alignLeft – Выравнивает левый край элемента с левым краем указанного элемента
android:layout_alignRight – Выравнивает правый край элемента с правым краем указанного элемента
android:layout_alignTop – Выравнивает верхнюю часть элемента в соответствие с верхней частью указанного элемента

TableLayout

TableLayout — табличная верстка.
Организует элементы в строки и столбцы таблицы.
Для организации строк служит таг

Alternate Layouts

Alternate Layouts — альтернативная верстка. Позволяет использовать различную верстку для различных ориентаций экрана.
XML для альтернативной верстки помещается в папки проекта:

res/layout-land – альтернативная верстка для landscape UI
res/layout-port –альтернативная верстка для portrait UI
res/lauout-square – альтернативная верстка для square UI

и перед тем как получить макет из res/lauout система проверяет наличие файлов в этих папках.

И в завершении немного о стилях.

Стили

Во первых стили элемента могут быть описаны в атрибутах самого элемента.
Например:

Кроме того стили можно вынести в отдельный xml файл и сохранить его в папке res/values/
Напимер:

Если мы вынесем стили в отдельный файл, то для описания стилей элемента будем использовать атрибут style.

Источник

Framelayout android для чего используется

Frame Layout is one of the simplest layout to organize view controls. They are designed to block an area on the screen. Frame Layout should be used to hold child view, because it can be difficult to display single views at a specific area on the screen without overlapping each other.

We can add multiple children to a FrameLayout and control their position by assigning gravity to each child, using the android:layout_gravity attribute.

Table Of Contents

Attributes of Frame Layout:

Lets see different properties of Frame Layout which will be used while designing Android App UI:

1. android:id

This is the unique id which identifies the layout in the R.java file.

Below is the id attribute’s example with explanation included in which we define the id for Frame Layout.

2. android:foreground

Foreground defines the drawable to draw over the content and this may be a color value. Possible color values can be in the form of “#rgb”, “#argb”, “#rrggbb”, or “#aarrggbb”. This all are different color code model used.

Читайте также:  Этот партнер не принимает входящие соединения teamviewer android

Example: In Below example of foreground we set the green color for foreground of frameLayout so the ImageView and other child views of this layout will not be shown.

Important Note: On applying android:foregroud feature, all the views taken in the framelayout will goes to the background and the framelayout comes in the foreground i.e. over the views. We can set the @drawable/image_name or the color in the foreground.

3. android:foregroundGravity

This defines the gravity to apply to the foreground drawable. Default value of gravity is fill. We can set values in the form of “top”, ”center_vertical” , ”fill_vertical”, ”center_horizontal”, ”fill_horizontal”, ”center”, ”fill”, ”clip_vertical”, ”clip_horizontal”, ”bottom”, ”left” or ”right” .

It is used to set the gravity of foreground. We can also set multiple values by using “|”. Ex: fill_horizontal|top .Both the fill_horizontal and top gravity are set to framelayout.

In the above same example of foreground we also set the foregroundGravity of FrameLayout to fill.

4. android:visibility

This determine whether to make the view visible, invisible or gone.

visible – the view is present and also visible

invisible – The view is present but not visible

gone – The view is neither present nor visible

5. android:measureAllChildren

This determines whether to measure all children including gone state visibility or just those which are in the visible or invisible state of measuring visibility. The default value of measureallchildren is false. We can set values in the form of Boolean i.e. “true” OR “false”.

This may also be a reference to a resource (in the form “@[package:]type:name“) or theme attribute (in the form “?[package:][type:]name“) containing a value of this type.

Important Note: If measureallchildren is set true then it will show actual width and height of frame layout even if the views visibility is in gone state.

The above property has been explained below:

Example of Frame layout having measureAllChildren attribute:

In the below code the ImageView visibility is set gone and measureAllChildren is set true. The output will show actual height and width the Frame Layout despite visibility is set gone. We have used Toast to display the height and width:

Below is the Code of activity_main.xml

Important Note: Make sure you have image in Drawable folder. In our case we have used ic_launcher image which we added in Drawable.

Below is the code of MainActivity.java . Here we have used Toast to display height and width on screen.

Читайте также:  Telegram android play store

When you run the App in Emulator you will see the below output:

Explanation of Example: It measures all the children in the layout. For ex: If we setVisiblity of an view be gone and set measuresAllChildren property to be true, then also it will also count to that view which is not visible, but if we set the measuresAllChildren property to be false, then it will not count to that view which is gone.

Things To Do Yourself: Try changing measuresAllChildren value to false and run the App in Emulator. You will see the output shows 0 width and height of Frame Layout.

Example Of Frame Layout in Android Studio:

Example 1: Frame Layout using layout gravity. Here we will put textview at different position in Frame Layout. Below is the code and final output:

Step 1: Create a new project in Android Studio and name it FrameTesting. (Select File -> New -> New Project. Fill the forms and click “Finish” button)

Step 2: Now Open res -> layout -> activity_main.xml and add the following code. Here we are putting different TextView in Frame Layout.

Step 3: Let the MainActivity.java has default Android code or add the below code:

Output:

Run the App in Emulator, you will see Textview positioned at various position in FrameLayout

Example 2: Example of A Frame Layout without using layout gravity. Here we will use a image to fill complete screen and then we will write “abhiandroid” text in center of the image. We will do all this inside Frame Layout. Below is the code and final output:

Step 1: Create a new project and name it FrameWithoutGravity.

Select File -> New -> New Project in Android Studio. Fill the forms and click “Finish” button.

Step 2: Now open res -> layout -> activity_main.xml and add following code. Here we are designing ImageView and TextView inside Frame Layout.

Important Note: Make sure you have an image saved in drawable folder name img_name. If you have saved other image with different name then please change it in the code.

Step 3: Let the MainActivity.java has default java code or add the below code:

Output:

Now run the App in Emulator and you will see the below output of Frame layout without Gravity:

Example 3 (BONUS): Another Example Of Creating A Frame Layout programmatically( i.e. Using Java Class only). Here we will create the same output as above but we won’t use xml. Instead we will use JAVA class. Below is code and final output:

Step 1: Create a new project in Android Studio. In our case we created FrameLayoutJAVA.

Источник

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