- Android collapsing toolbar constraint layout
- Collapsing Toolbar Layout Example
- How to use collapsing toolbar layout
- Collapsing toolbar layout output
- Collapsing toolbar layout code
- Layout xml
- Activity
- Collapsing toolbar layout title configuration
- Styles.xml
- Parallax scrolling and pinned position childern
- About
- Как декларативно описать коллапсирующий тулбар
- Термины
- Зачем понадобилось писать свое решение
- Как выглядит апи
- Как это работает
- TutorialsBuzz
- Build Gradle
- XML Layout
- MainActivity
- Creating an interactive and collapsible toolbar on Android
- The layout
- The code
- Disabling the collapse / expand animation
- Dániel Zolnai
Android collapsing toolbar constraint layout
Collapsing Toolbar Layout Example
December 19, 2016 by Srinivas
CollapsingToolbarLayout is provided to help in creating toolbars that follow material design. It is a wrapper for tool bar adding additional features to toolbar in the coordinator layout and app bar layout context.
Collapsing toolbar layout should be used as a child of app bar layout. To make functionality provided by app bar layout work, app bar layout needs to be part of coordinator layout. Collapsing toolbar layout, app bar layout and coordinator layout framework is provided in design support library.
To use these layouts in your project, you need to include design support library by adding below dependency in your gradle build file.
For more information about coordinator layout and app bar layout, please read coordinator layout and app bar layout related articles.
How to use collapsing toolbar layout
Collapsing toolbar layout allows you to customize toolbar in app bar layout meaning depending on positional changes applied to tool bar by app bar layout and coordinator layout, collapsing toolbar layout lets you configure toolbar, changing tool bar UI experience.
Collapsing toolbar layout output
Collapsing toolbar layout code
Layout xml
Activity
Collapsing toolbar layout title configuration
As seen above, collapsing toolbar layout title can be set using setTitle method. You can apply different text styles for collapsing and expanding toolbar.
Styles.xml
Parallax scrolling and pinned position childern
Attribute layout_collapseMode controls how child views of collapsing toolbar layout move when layout is moving. If layout_collapseMode of a view is set to parallax, it moves in parallax fashion. When layout_collapseMode attribute is set to pin, view is placed in a fixed position. Below screens show toolbar when layout_collapseMode is set to pin and without the layout_collapseMode setting.
About
Android app development tutorials and web app development tutorials with programming examples and code samples.
Источник
Как декларативно описать коллапсирующий тулбар
Хочу представить решение того, как можно описать CollapsingToolbar, с акцентом на читаемости кода. В статье не будет объясняться, что такое и как написать свой CoordinatorLayout.Behavior. Если читателю интересно в этом разобраться, есть много статей, в том числе на хабре. Если разбираться не хочется — ничего страшного: я постарался вынести написание CollapsingToolbar так, чтобы можно было абстрагироваться от CoordinatorLayout.Behavior и OnOffsetChangedListener.
Термины
Зачем понадобилось писать свое решение
Я просмотрел несколько подходов в «интернетах», и практически все были построены следующим образом:
- Задается фиксированная высота для AppBarLayout.
- Пишется CoordinatorLayout.Behavior, в котором какими-то вычислениями (закешированная высота view складывается с bottom другого view и за вычетом margin умножается на проскролл, вычисленный здесь же) меняют какую-то вью.
- Другие вью меняют в OnOffsetChangedListener AppBarLayout-а.
Вот пример Behavior с описанным подходом, 2.5к звезд на Гитхабе.
Поправить верстку для этого решения можно, но меня смущает другое. Некоторые вью управляются через OnOffsetChangedListener, некоторые — через Behavior, что-то работает из коробки. Разработчику, чтобы понять всю картину, придется пробежаться по множеству классов, и если для новой вью придется добавить поведение, которое зависит от других Behavior-ов и от вью, которые изменяются в OnOffsetChangedListener, могут вырасти костыли и баги на ровном месте
Кроме того, в данном примере не показано, как быть, если в тулбар будут добавляться дополнительные элементы, которые влияют на высоту этого тулабара.
В гифке в начале статьи видно, как по нажатию на кнопку скрывается TextView — и NestedScroll подтягивается выше, чтобы не возникало пустого пространства).
Как это сделать? Решения, которые первыми приходят на ум, — написать еще один CoordinatorLayout.Behavior для NestedScroll (сохранив логику базового AppBarLayout.Behavior) или засунуть тулбар в AppBarLayout и менять его на OnOffsetChangedListener. Я пробовал оба решения, и получался завязанный на детали реализации код, с которым довольно сложно будет разобраться кому-то другому и нельзя будет переиспользовать.
Буду рад, если кто-то поделится примером, где такая логика реализована «чисто», а пока покажу свое решение. Идея в том, чтобы иметь возможность декларативно описать в одном месте, какие вьюхи и как должны себя вести.
Как выглядит апи
Итак, для создания CoordinatorLayout.Behavior нужно:
- унаследовать BehaviorByRules;
- переопределить методы, возвращающие AppBarLayout, CollapsingToolbarLayout и длину скролла (высоту AppBarLayout).
- переопределить метод setUpViews — описать правила, как вью будет себя вести при измененнии проскролла аппБара.
TopInfoBehavior для тулбара из гифки в начале статьи будет выглядеть так (далее в статье объясню, как это работает):
Как это работает
Задача сводится к написанию правил:
Тут все ясно — приходит float-значение от 0 до 1, отражающее процент проскролла ActionBar, приходит вью и ее первоначальный стейт. Интереснее выглядит BaseBehaviorRule — правило, от которого наследуются другие базовые правила.
Для базовых правил определяется размах значений (min, max) и interpolator. Этого хватит для того, чтобы описать практически любое поведение.
Допустим, мы хотим задать альфу для нашего вью в диапазоне 0.5 до 0.9. Также мы хотим, чтобы вначале скролла вью быстро становилась прозрачной, а затем скорость изменений падала.
Правило будет выглядеть так:
А вот реализация BRuleAlpha:
И, наконец, код BehaviorByRules. Для тех, кто писал свой Behavior, все должно быть очевидно (кроме того, что внутри onMeasureChild, об этом расскажу ниже):
Так что там с onMeasureChild?
Это нужно для решения проблемы, о которой писал выше: если какая-то часть тулбара исчезает, NestedScroll должен подъехать выше. Чтобы он подъехал выше, нужно уменьшить высоту CollapsingToolbarLayout.
Есть еще один неочевидный метод — canUpdateHeight. Он нужен, чтобы можно было разрешить наследнику задать правило, когда нельзя менять высоту. Например, если view, от которого зависит высота, в данный момент скрыта. Не уверен, что это покроет все кейсы, но если у кого есть идеи, как сделать лучше, — отпишите, пожалуйста, в комментарии или в личку.
Источник
TutorialsBuzz
With the new Design support library for Android, it has become easier for us to create some great animations with minimal effort , CollapsingToolbarLayout is the newly introduced in Lollipop , using which you can create awesome scrolling effects . With the new Design support library for Android, it has become easier for us to create some great animations with minimal effort .
Build Gradle
Add the following lines to the dependencies section in your project’s build.grade file and sync .
It include design support library , cardview library and palette library .
XML Layout
Create XML layout file in res/layout and name it activity_main.xml
Is essentially a LinearLayout (vertical). It helps respond to its children’s scroll events (scroll gestures). Responsible for implementing many features of material design’s app bar. Depends heavily on being used as a direct child within CoordinatorLayout.
It’s an special scroll view for the smooth scrolling effect, inside this place the desired content . Here in this example will add several Cards as its children.
Flags include :
- scroll: this flag should be set for all views that want to scroll off the screen — for views that do not use this flag, they’ll remain pinned to the top of the screen.
- enterAlways: this flag ensures that any downward scroll will cause this view to become visible, enabling the ‘quick return’ pattern .
- enterAlwaysCollapsed: When your view has declared a minHeight and you use this flag, your View will only enter at its minimum height (i.e., ‘collapsed’), only re-expanding to its full height when the scrolling view has reached it’s top.
- exitUntilCollapsed: this flag causes the view to scroll off until it is ‘collapsed’ (its minHeight) before exiting .
Note : all views using the scroll flag must be declared before views that do not use the flag.This ensures that all views exit from the top, leaving the fixed elements behind.
For CollapsingToolbarLayout XML Tag set the layout_scrollFlags property with
scroll|exitUntilCollapsed
Collapse Mode
- Parallax scrolling with the ImageView is achieved by simply setting its layout_collapseMode to parallax.
- The Toolbar must use pin as its collapseMode because we want the Toolbar to persist and remain on top as the user scrolls down.
The XML Layout Inflate the view as below.
MainActivity
Now Inside the Activity we will see how to change the TextAppearance and Coloring of Toolbar Dynamically when Collapsing Toolbar expands and collapse .
1. Dynamic TextAppearance :
A title which is larger when the layout is fully visible but collapses and becomes smaller as the layout is scrolled off screen. The title appearance can be tweaked via the collapsedTextAppearance and expandedTextAppearance attributes .
Add the following style code inside the style.xml .
2. Dynamic Toolbar Coloring :
We’ll pass our image view’s bitmap to the Palette API, which will generate colors based on the image in an PaletteAsyncListener. Upon completion, we can fetch the color we want and set it to our CollapsingToolbarLayout, which in turn will color our Toolbar when we scroll up.
The Complete MainActivity Source code
Scrolling Effect with Dynamic TextAppearance and Toolbar Coloring According to Image
Источник
Creating an interactive and collapsible toolbar on Android
Let’s say we have an expanding / collapsing toolbar, and we want to add an extra interactive element to it: the title should have an extra chevron next to it, and when you click on the title, it should rotate 180 degrees, and open a popup menu, like this:
It seems easy, on a first glance we would probably have to retrieve the TextView used by the CollapsingToolbarLayout to retrieve the TextView, add a right compound drawable and a click listener, and that’s it, right?
Well, the problem is, that there’s no TextView at all. The relevant code is inside the CollapsingTextHelper class, and it turns out that the collapsing text is created by drawing on the View canvas directly. Instead, we will have to rely on the feature that we can put custom widgets inside the toolbar, and manipulate those so that they look as they are connected to the text.
The layout
Our layout XML code will look like this:
It is quite long and complicated, but let’s go through it from top to bottom:
First of all, you have CollapsingToolbarLayout , with its usual properties. With its app: properties we position and style the collapsed/expanded text to our taste. That was already part of our setup before.
The first widget inside the layout is a Space . The size of the largest widget inside the CollapsingToolbarLayout dictates its expanded size. That’s what I use this layout for.
The next layout in order is the Toolbar itself. It contains some extra properties to put the text at the correct place (left and right margins), this layout can also be used to put some extra widgets inside, like a cast button on the right.
The next view is a clickable layout, with the chevron in it. We will try to position this layout exactly where the text is, changing its size and height while collapsing. The chevron inside is just a regular ImageView which we will rotate on the click action.
Finally, we have a back button touch forwarder, positioned exactly above the back button. See why this is required in the following section.
The code
We tie into the AppBar offset listener to detect what the collapse status is of the toolbar.
First we need to detect if the offset changed. Because we change the layout inside the listener, it will trigger a new call on the same listener. If we would not check for this, we will get inside an infinite loop.
Next we use the knowledge that we have all the font, text size info from the collapsed and expanded states. Using those, and the current collapse offset, we calculate the exact width an position of the clickable layout, and position it.
Now we can add a click listener, which hides or show the popup window:
Finally, the back button touch forwarder. We need to put our clickable layout above the Toolbar , because the Toolbar ‘eats’ all touch events. But when the clickable layout is on top, the back button would be mostly hard to click, because the text gets quite close.
Our solution is putting an extra View on top of our clickable layout, which is exactly the size and position as the back button, and all it does is forward its touch events to the Toolbar below it.
Disabling the collapse / expand animation
A feature we wanted to have is to disable the expand animations on the toolbar, and just have it locked in the same place. Also we would like to reuse the toolbar code for this, so we don’t have to style it again.
When we call this code, it will set the toolbar in a collapsed state immediately.
We set nested scrolling enabled on the content, so that it should not forward any scroll calls, and we also change the Coordinator behavior on the AppBar layout, so that dragging it manually does also not expand it.
Finally, we set the visibility of the extra widgets to gone, because those would suggest interactivity.
With this, we get our end result:
You can try out the code yourself here
Dániel Zolnai
Usually, Dániel has already done the job before you have even asked him to start. And he always delivers top quality work. This has made him our in-house psychic. He does not do Toto-forecasts however, which is a bummer.
Источник