App bar layout android studio

Овладение Coordinator Layout

На презентации Google I/O 15, компания Google представила новую версию библиотеки поддержки которая реализует несколько компонентов, сильно связанных со спецификациями Material Design, среди этих компонентов вы можете найти новые типы ViewGroup такие как AppbarLayout , CollapsingToolbarLayout и CoordinatorLayout .

При правильном комбинировании и настройке данные Viewgroup могут быть очень мощным инструментом, по этому я решил написать статью с некоторыми настройками и советами.

CoordinatorLayout

Как и предполагает его название, цель и философия этой ViewGroup является координация view элементов, которые находятся внутри него.

Рассмотрим следующую картинку:

В этом примере можем видеть как view элементы размещены друг относительно друга, не прибегая к детальному просмотру, мы видим как одни View зависят от других. (мы поговорим об этом позже).

Это будет простейшая структура использования CoordinatorLayout :

Рассмотрим скелет данного layout. У этого CoordinatorLayout имеется только три дочерних элемента: AppbarLayout , прокручиваемый view и закрепленный FloatingActionBar .

AppBarLayout

Проще говоря, AppBarLayout это LinearLayout на стероидах, их элементы размещены вертикально, с определенными параметрами элементы могут управлять их поведением, когда содержимое прокручивается.

Это может прозвучать запутано сначала, но как, — «Лучше один раз увидеть, чем сто раз услышать», к вашему вниманию .gif-пример:

В данном случае AppBarLayout это синяя view, размещенная под исчезающим изображением, она содержит Toolbar , LinearLayout с заголовком и подзаголовком и TabLayout с несколькими вкладками.

Мы можем управлять поведением элементов AppbarLayout с помощью параметров: layout_scrollFlags . Значение: scroll в данном случае присутствует почти во всех элементах view, если бы этот параметр не был указан ни в одном из элементов AppbarLayout, он остался бы неизменным, позволяя прокручиваемому контенту проходить позади него.

Со значением: snap , мы избегаем попадания в полу-анимационного-состояния, это значит, что анимация всегда скрывает или отображает полный размер view.

LinearLayout который содержит заголовок и подзаголовок будет всегда отображен при прокручивании вверх, ( enterAlways значение), и TabLayout будет видим всегда так как на него не установлен ни один флаг.

Как видите настоящая мощь AppbarLayout определяется должным управлением его флагами прокрутки в определенных view.

Все эти параметры доступны в документации Google Developers. В любом случае, я рекомендую поиграть с примерами. В конце статьи размещены ссылки на репозитории Github с реализацией примеров.

Флаги AppbarLayout

SCROLL_FLAG_ENTER_ALWAYS : При использовании флага, view будет прокручиваться вниз не зависимо от других прокручиваемых view.
SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED : Дополнительный флаг для ‘enterAlways’, который изменяет возвращаемый view к изначально прокручиваемому, при исчезновении высоты.
SCROLL_FLAG_EXIT_UNTIL_COLLAPSED : При выходе, view будет прокручен до тех пор пока не исчезнет.
SCROLL_FLAG_SCROLL : Элемент view будет прокручиваться в направлении события прокрутки.
SCROLL_FLAG_SNAP : В конце прокрутки, если view видим только частично, он будет докручен до его ближайшего края.

CoordinatorLayout Behaviors

Проведем не большой эксперимент, запустим Android Studio (>= 1.4) и создадим проект из шаблона: Scrolling Activity, ничего не изменяя, компилирием и вот что мы видим:

При рассмотрении сгенерированного кода, ни макеты layout ни java классы не имеют ничего относящегося к маштабированию анимации плавающей кнопки при прокрутке. Почему?

Ответ находится в исходном коде FloatingActionButton , с тех пор как Android Studio v1.2 включает java декомпилятор, с помощью ctrl/cmd + click мы можем проверить исходный код и посмотреть что происходит:

За маштабирование анимации отвечает новый элемент, представленый вместе с design library, под названием Behavior . В данном случае , который зависит от некоторых факторов включая прокрутку, показывать FAB или нет, интересно, не правда ли?

SwipeDismissBehavior

Продолжим углубление в код, если вы посмотрите внутрь пакета виджетов design support library, то сможете найти открытй клас под названием: SwipeDismissBehavior . С этим новым Behavior мы можем очень легко реализовать функцию свайп для отмены в наших шаблонах с CoordinatorLayout :

Custom Behaviors

Создать свой шаблон поведения (Behavior) не так и сложно как может показаться, для начала мы должны принять во внимание несколько основных элементов: child и dependency.

Child и dependency

child это элемент который усиливает поведение, dependency — тот кто будет обслуживать его как тригер для взаимодействия с child элементом. Посмотрим на пример, child — элемент ImageView, а dependency это Toolbar, таким образом, если Toolbar движется, ImageView тоже движется.

Читайте также:  Менеджер шрифтов андроид вирус

Теперь, когда мы определили концепт, можем поговорить о реализации, первым шагом будет наследование от:
, значение T будет класс который принадлежит view, что необходим нам для координации, в данном случае ImageView, после чего мы должны переопределить следующие методы:

  • layoutDependsOn
  • onDependentViewChanged

Метод: layoutDependsOn будет вызван каждый раз когда что-то случится в layout, чтобы вернуть true , как только мы определили dependency, в примере, этот метод срабатывает автоматически при прокручивании (т.к. Toolbar будет двигаться), таким образом, мы можем подать знак нашему child отреагировать соответствующим образом.

Всякий раз когда layoutDependsOn возвращает true будет вызван второй onDependentViewChanged . Вот тут-то мы и должны реализовать нашу анимацию, перевод или движения всегда зависят от предоставленной зависимости.

Источник

Android AppBarLayout And Toolbar Example

android.support.design.widget.AppBarLayout is used to wrap android.support.v7.widget.Toolbar component. It can make the Toolbar avoid being overlapped by ListView or RecyclerView controls in the screen.

1. How To Control Android App Toolbar Show / Hide Behavior.

  1. Wrapped by AppBarLayout, the Toolbar will be hidden when the user scrolls RecyclerView down, and it will be shown again when the user scrolls RecyclerView up. You can set the behavior by configuring Toolbar‘s app:layout_scrollFlag property value as below.
  2. The Toolbar property app:layout_scrollFlags‘s value can be followings.
  3. scroll: Scroll means when the RecyclerView scrolls up, the Toolbar will scroll up also and be hidden.
  4. snap: Snap indicates that when Toolbar is not fully hidden or displayed, it will automatically select whether it is hidden or displayed on the basis of the current rolling distance.
  5. enterAlways: This means when RecyclerView scrolls down, the Toolbar will scroll down and display again.

2. Scroll RecyclerView To Show / Hide Toolbar Example.

    1. In this example, there is a Toolbar and a RecyclerView on the screen. The Toolbar contains two menu items Add and Delete. The RecyclerView use LinearLayoutManager to list some car image and text.
    2. When clicking the Add menu item, it will add a car to the list randomly, when clicking the Delete menu item, it will automatically delete a car in the list also.

Below is the screen without use AppBarLayout to wrap Toolbar.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/FRkDIDS05MI

Below is the screen that uses AppBarLayout to wrap the Toolbar component.

Источник

Android AppBarLayout

1 is what I want to archive, but what it looks like atm is 2

I tried almost every solution on Stack Overflow,

I don’t think it should be this difficult. Any suggestions or example projects are appreciated.

2 Answers 2

Sebastian I had the same problem before , after playing around with fitssystemwindows attribute , it was fixed. I don’t exactly remember what I had done , don’t even know what that attribute does . So you can try different combinations adding/removing fitssystemwindows too. For example , remove it from appbarlayout and see what happens.

I just figured it out, but I don’t know how.

I tried all the possible android:fitsSystemWindows=»true» combinations before but none of the combination worked, but after I changed bunch of layouts, it’s just suddenly fixed.

I tracked down every single lines of code changes, and it turned out I should remove android:fitsSystemWindows=»true» option from the AppBarLayout .

It’s really weird because I tried exactly the same thing about 3 times before, but it didn’t have any effect on the layout.

I think it’s probably a caching issue or some bug on annoying Android Studio again..

If anyone suffer from similar issues with me, I would recommend 1. clean project 2. remove the layout entirely and put it back to see the actual changes

I wasted about 5 hours on this problem and the lesson is just «don’t trust Android Studio»

Источник

Using Coordinator Layout in Android

You all must have used FrameLayout in your Android applications and must be familiar with the difficulties that we face while managing the views in a FrameLayout especially when having some view over the other and things become worse when there is some animation present in the views. Also, it is advised not to use more than one element in our FrameLayout. The reason behind this is, you have to explicitly handle the motions or you may say the animations of all the views that are present on a particular page of your mobile application.

Читайте также:  Samsung pay android studio

So, in order to handle the views(especially the view that is having some motion) in a better way, Android introduced a new layout called the CoordinatorLayout. By using Coordinator layout you can easily handle and animate the transitions of views present in a Coordinator Layout.

To have a clear understanding of the usage of Coordinator Layout, please open your WhatsApp application. Now, open any chat and click on the name of the chat. You would see the profile pic and other details of that contact. Now try to scroll down the page. Did you see any change in the profile pic? Yeah, it disappeared and now only the contact name is visible. Now, scroll up and the profile pic will be visible again. This is done with the help of CoordinatorLayout. Another example of Coordinator Layout can be seen below:

Here, we can see that one view is going over the other and the transaction or animation between these views is very smooth. That’s the power of CoordinatorLayout.

So, welcome to MindOrks! In this blog, we are going to learn about CoordinatorLayout in Android. We will see various use-cases of the Coordinator Layout with the help of an Android Studio project.

The following is the timeline of the blog:

  • What is the Coordinator Layout?
  • Behaviors in Android application
  • Project Setup
  • Implementing Scroll-Based Behavior
  • Implementing Layout-Based Behavior

What is Coordinator Layout?

According to the official documentation of Android:

CoordinatorLayout is a super-powered FrameLayout.

At the Google I/O 2015, Google introduced Coordinator Layout to remove the difficulties of having more than one layouts in FrameLayout. Now, with the help of the CoordinatorLayout, the interaction between the views become very easy even in the case of animation. CoordinatorLayout controls the animation and transactions of various child elements with one another. We have seen some examples of CoordinatorLayout in the introduction section of the blog. After looking at the examples, one question that might come in your mind is that how the CoordinatorLayout knows what to do with the child present in CoordinatorLayout? Let’s try to find the answer.

Behaviors in Android Application

Whenever a view is interacting with the other then it is done with the help of Behaviors. We create a particular behavior for a particular view and these behaviors are responsible for animations between the views. Some of the common Material Design behaviors are sliding drawers, swipe-dismissal, floating action button, a sticky button that stick on some other view. So, broadly these behaviors can be classified into two types:

  1. Layout-Based: Layout-Based behaviors are used to shift one view to some other place when you perform a certain operation. For example, whenever you click on a Floating Action Button(FAB), then that FAB will be moved up and one Snackbar will come from the bottom of the screen. After a few seconds, the Snackbar will be gone and the FAB will come to its original place.
  2. Scroll-Based: Scroll-Based behaviors are the most common use of Coordinator Layout. Here, these behaviours are based on the scroll gesture of the user on the mobile screen. Remember the example of WhatsApp, that we discussed in the introduction section. When you scroll the profile or contact page in WhatsApp, then you will find that the profile image will be changed to ActionBar. So, these types of behaviors are called Scroll-Based behaviors.

Project Setup

  • Open Android Studio and create a project
  • Activity: EmptyActivity
  • Project Name: CoordinatorLayout-Example
  • Language: Kotlin

In order to use the CoordinatorLayout in your project, you need to add the CoordinatorLayout dependency in your project. Also, we will be using some material design components. So, add the below dependency in the app level build.gradle file:

So, in this example, we will see both behaviors i.e. the layout-based and the scroll-based. So, in the MainActivtiy, we will have two buttons, one for each behavior and then two different activities for these two. So, here is the code of the activity_main.xml file:

And the code for opening the two activities on button click will be in the MainActivity.kt file. Here is the code for the same:

Читайте также:  Лучший андроид до 120

Now, we need to create two activities i.e. one for layout-based and other for scroll-based. So, create two EmptyActivity named:

Now, let’s see one by one.

Implementing Scroll-Based Behavior

Scroll-Based behaviors are mostly used behaviors. Here we scroll one view to overlap on to the other view.

So, here in this example, we will implement the same behavior as used in the WhatsApp application.

We have already created the ScrollBasedActivity, so let’s use the same.

The layout of this file contains:

  • A CoordinatorLayout as the base layout
  • An AppBarLayout and a FAB as a child of the CoordinatorLayout
  • And finally, a CollapsingToolbarLayout as a child of AppBarLayout

Here is the code of activity_scroll_based.xml :

While using the CollapsingToolbarLayout, you need to know two important things i.e.

These flags are used to specify the type of collapsing to be done. These can be used singly and with each other also.,

  • scroll: When you scroll up then the collapsed view will be visible when you reach to the top. When you scroll down, the view will be scrolled just like any other ScrollView.

  • enterAlways: When you scroll up then the view becomes visible irrespective of your current position. When you scroll down, the view will be scrolled just like any other ScrollView.

  • enterAlwaysCollapsed: When you scroll up then the collapsed view will be visible(for example, the toolbar will be visible here) and expands(the ImageView or any other view used) when you reach to the top of the page. When you scroll down then the view(both toolbar and ImageView) will be collapsed.

  • exitUntilCollapsed: When you scroll up then the view(the toolbar) will be visible and to see the expanded version of the view(having ImageView and other views) you need to scroll to the top of the page. When you scroll down, normal scrolling will be seen just like any other ScrollView.

  • snap:It scrolls based on the visibility of the view. If the visibility is more than 50% then the view will show itself and if it is less then it will hide.

This indicates the type of effect while collapsing the view.

  • parallax: This is generally used with images to provide a parallax effect. The image will become in
  • pin: The view will be pinned to its position. It is generally used with toolbars when you need to keep the toolbar even after collapsing the other views.

The code for the ScrollBasedActivity.kt will be:

Run the application and try to scroll up and down. Also, you can use various flags and run the app to see the changed behavior.

Implementing Layout-Based Behavior

Here in this activity, we will create a Floating Action Button and on clicking the FAB, a Snackbar will come from the bottom of the screen and it will be disappeared after a few seconds.So, here is what we will have in our Activity:

  • A CoordinatorLayout as our base layout
  • Inside the base layout, we will have an AppBarLayout, a floating action button, and some content for the page.

Here is the code for the same:

Now, create a layout file named content_layout_based_activity in the res > layout directory. This file contains the main content of the LayoutBasedActivity. For simplicity, I will use text but you can replace it according to your use-case.

Here is the code for the content_layout_based_activity :

And finally, you need to handle the click of the floating action button in the LayoutBasedActivity.kt file:

All done, now you can run the app and click on the FAB to see the layout behavior in your application.

Conclusion

In this blog, we learned how to use Coordinator Layout in our application. Coordinator Layout is used to manage the transactions and animation of various views present in an Activity. Before Coordinator Layout, Frame Layout was used, but using more than one views in Frame Layout results in overlapping of views over one another. At the end of the blog, we did some examples to have a clear understanding. Hope you enjoyed the blog.

Источник

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