How to do the new PlayStore parallax effect - android

Does anyone know how can I achieve the new parallax scrolling effect - you can see the effect when you open an app on the PlayStore and try to scroll down, the content goes over the top image. How can I achieve that?

Google has recently announced Design support library and with this it has support for implementing Collapsing Toolbar.
In addition to pinning a view, you can use
app:layout_collapseMode="parallax" (and optionally
app:layout_collapseParallaxMultiplier="0.7" to set the parallax
multiplier) to implement parallax scrolling (say of a sibling
ImageView within the CollapsingToolbarLayout)
Example:
<android.support.design.widget.AppBarLayout
android:layout_height="192dp"
android:layout_width="match_parent">
<android.support.design.widget.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<android.support.v7.widget.Toolbar
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"
app:layout_collapseMode="pin"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

You could try this (FadingActionBar library):
https://github.com/ManuelPeinado/FadingActionBar
Try an example of this library on android: https://play.google.com/store/apps/details?id=com.manuelpeinado.fadingactionbar.demo
EDIT: Rather than third party library use this AppBarLayout and CollapsingToolbarLayout http://android-developers.blogspot.in/2015/05/android-design-support-library.html

try the ObservableScrollView library
https://github.com/ksoichiro/Android-ObservableScrollView
demo application from play store
https://play.google.com/store/apps/details?id=com.github.ksoichiro.android.observablescrollview.samples2
sample demo,

Actually few minutes after posting this question I bumped on two of libraries that do the effect I'm looking for and even more.
Here are links to them:
Parallax Scrolls
Paralloid

There's a library called FadingActionBar that does exactly what you're asking for. You can find the library on GitHub (click) and a Demo-Application in the Play Store (click).
Usage would be something like this:
FadingActionBarHelper helper = new FadingActionBarHelper()
// Set the ActionBar drawable - basically the color
.actionBarBackground(R.drawable.ab_background)
// Set the Header - usually an image
.headerLayout(R.layout.header)
// Set the main layout
.contentLayout(R.layout.activity_scrollview);
setContentView(helper.createView(this));
helper.initActionBar(this);

You may custom the parallax animation by tracking the Recycler View Scrolling
Firstly in the image view layout. Set the parent layout is smaller than image view so that prevent the image outside the bound when set translationY
<android.support.percent.PercentRelativeLayout
android:id="#+id/index_level6_image_section"
android:layout_width="match_parent"
android:layout_height="200dp"
android:clipChildren="false">
<ImageView
android:id="#+id/index_level6_parallaxImage"
android:layout_width="match_parent"
android:layout_height="240dp"
android:layout_centerInParent="true"
android:background="#color/timberwolf"
android:layout_marginTop="-20"
android:layout_marginBottom="-20"
android:scaleType="centerCrop"
app:imageUrl="#{level6CellViewModel.level6ImageUrl}" />
</android.support.percent.PercentRelativeLayout>
After that, track the recycler view scrolling effect and transitionY the image view.
*** I am using rxbinding and kotlin for implementation. You may use traditional listening method and java approach with the same idea.
RxRecyclerView.scrollEvents(recyclerView)
.subscribe { event ->
// get the visible cell items of the recycler view
val firstVisible = layoutManager.findFirstVisibleItemPosition()
val visibleCount = Math.abs(firstVisible - layoutManager.findLastVisibleItemPosition())
/** loop the visible cell items from the recycler view */
for (i in firstVisible..firstVisible + visibleCount) {
event.view().layoutManager?.findViewByPosition(i)?.let { cellItem ->
/** only for index cell level 6 parallax image */
cellItem.findViewById(R.id.index_level6_parallaxImage)?.let { imageView ->
/** setting the parallax effect */
val translationY = (cellItem.top - cellItem.height) / level6ParallaxRate
imageView.translationY = -translationY
}
}
}
}

Related

Android sticky CollapsingToolbarLayout in AppBarLayout

I want to add a behaviour to my CollapsingToolbarLayout such that the "collapsible" content is sticky (image) in this case. Only the bottom sheet needs to be scrollable and it will overlay the images in the ViewPager. Attaching recording video for better understanding.
https://www.youtube.com/shorts/trmpy__f9Is
The expected behaviour is as shown the image below where the header should stick and footer should overlay it when scrolled.
Code is something like this-
<androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.appbar.AppBarLayout>
<com.google.android.material.appbar.CollapsingToolbarLayout
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<androidx.viewpager2.widget.ViewPager2/>
<androidx.appcompat.widget.Toolbar />
<ConstraintLayoutForSomeContent/>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Also tried playing with app:layout_collapseMode="pin" and app:layout_scrollFlags="noScroll" to CollapsibleToolbarLayout, AppBarLayout with no luck.
The other option was not making ViewPager part of the CollapsibleToolbarLayout which solves the purpose but then the ViewPager is not scrollable anymore as the touch is consumed by the overlaying CollapsibleToolbarLayout.
Is there a way this can be achieved.
Try This
add the below line in your view pager
app:layout_collapseParallaxMultiplier="1.0"
change the value you want between 1 to 0.9

Loading items into a RecyclerView with stackFromEnd = true doesn't scroll to bottom

I have a chat app and i'm trying to ensure that when the user opens the screen the items display from the bottom with the most recent right above the input area. I've used a custom view for the input area and both the recycler and the custom view are within a ConstraintLayout.
My problem is that when I load items into the list, if the number of items is greater than the size of the recycler, it will not fully show the last item. When I make the input area visibility = Gone then the items display properly at the bottom. It's almost like the recyclers LinearLayoutManager thinks that the height of the Recycler is of the screen without the input field. I've manually printed out the size of the views and used layout inspector to ensure that the recycler is indeed drawn in the correct location (above the input and below the navigation bar).
What could be causing such an issue? I should note that whenever you click on a Linkified text in a chat bubble that the list scrolls a small amount equal to the offset that's incorrect when you open the screen. Clearly something is not measuring right here and not sure where to begin.
I should also note that if I try to add a post with smoothScroll it will go to the end of the list but then whenever a new item appears in the list from sending a message the items above the most recently added one seem to jump up a little with an unnecessary animation. It's like the last item in the list is in some special state?
if you're curious this is my scrolling function:
private fun scrollToFirstItem(dueToKeyboard: Boolean = false) {
val stackingFromEnd = (recyclerView.layoutManager as LinearLayoutManager).stackFromEnd
if (stackingFromEnd) {
val firstPosition = recyclerView.adapter?.itemCount?: 0 - 1
if (dueToKeyboard ) {
recyclerView.scrollBy(0, Integer.MAX_VALUE)
} else {
recyclerView.scrollToPosition(firstPosition)
}
recyclerView.post { recyclerView.smoothScrollToPosition(firstPosition) }
} else {
recyclerView.scrollToPosition(0)
}
}
And my xml for my fragment:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/searchView"
layout="#layout/compose_new_message_include"/>
<com.airbnb.epoxy.EpoxyRecyclerView
android:id="#+id/conversationEpoxyRV"
android:layout_width="match_parent"
android:layout_height="0dp"
android:scrollbars="vertical"
app:layout_constraintTop_toBottomOf="#id/searchView"
app:layout_constraintBottom_toTopOf="#id/composeView"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
tools:listitem="#layout/conversation_item_inbound"/>
<include layout="#layout/conversation_pip_view"
android:id="#+id/selectedMediaContainer"/>
<****.ComposeView
android:id="#+id/composeView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Any help is appreciated, I'm so lost..
To me this feels like more of an issue in the layout rather than in the scrolling function. I hope that this can be resolved easily if you use a Relative Layout instead of a Linear Layout. So in case if it may be helpful, i'll add my solution below using a Relative Layout.
<RelativeLayout
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycle_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/input_field">
</androidx.recyclerview.widget.RecyclerView>
<EditText
android:id="#+id/input_field"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
So in case if it is not clear what i have done, an EditText element is set to align to the bottom of parent which is a Relative Layout. Then a RecyclerView is added so that RecylerView will be always constraint above the EditText but not overlapped.
Everything looks fine, except the restrictions you added to recycleview design, I see that you are setting the recycleview to top of searchView app:layout_constraintTop_toBottomOf="#id/searchView" while the searchView view is not restricted as should it be.
It's better when using ConstraintLayout to restrict every view inorder avoid unexpected behaviors, because every view has a relation with other view will be effected with other view (x, y), therefore your searchView should be look like:
<include
android:id="#+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
layout="#layout/compose_new_message_include"/>
Give the size of arraylist of your data to smoothScrollToPosition
var linearLayoutManager = LinearLayoutManager(context)
recyclerView.layoutManager=linearLayoutManager
recyclerView.adapter=adapter
linearLayoutManager.setStackFromEnd(true)
adapter.notifyDataSetChanged()
recyclerView.smoothScrollToPosition(dataMsgs.size())
I had a similar problem some years back and I solved it with scrollToPositionWithOffset (support library). Of course this was before constraint was used....
I kept my newer items at the bottom, too. The code I used for scrolling after inserting an item was:
((LinearLayoutManager) layoutManager).scrollToPositionWithOffset(getItemCount() - 1, 0);
To scroll and adjust the awkward positioning after removing an item, I used:
View vTopCard = layoutManager.getChildAt(0);
// Get its adapter position
final int topCardPos = layoutManager.getPosition(vTopCard);
// Get top of card position
int topOffset = layoutManager.getDecoratedTop(vTopCard);
int cardMargin = (int) getResources().getDimension(R.dimen.card_vertical_margin);
((LinearLayoutManager) layoutManager).scrollToPositionWithOffset(topCardPos, topOffset - cardMargin);
The getDecoratedTop helps with the "bounce" and final positioning, as does factoring the vertical margin.
I hope this helps (at least part of your issue)! Like I said, this is old code (when I was learning to program Android and Java at the same time), so if I left something out, let me know and I'll reexamine the app's code in more detail (though, I'll have to find the time).
Good luck!

Changing toolbar background alpha value when scrolling with CoordinatorLayout

I am currently trying to use the CoordinatorLayout class to adapt a Toolbar opacity depending on a ScrollView scroll position. I succeed doing this "manually linking" the two views, listening to the ScrollView scroll events and reporting them on the alpha value of my Toolbar background.
The wanted behavior is :
The toolbar is starting in a transparent state (both text and background) and end up totally white background and black text when one view is totally scrolled.
The behavior is roughly this one : Youtube video.
Current implementation
layout file (simplified)
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true">
<ScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<my.package.widgets.DetailsTop
android:id="#+id/layout_details_top"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<my.package.widgets.DetailsBottom
android:id="#+id/layout_details_bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00FFFFFF"/>
</RelativeLayout>
Fragment implementation
public class SearchVehicleDetailsFragment extends BaseFragment<SearchContract.ParentView> {
#Bind(R.id.layout_details_top) DetailsTop detailsTopLayout;
#Bind(R.id.layout_details_bottom) DetailsBottom detailsBottomLayout;
#Bind(R.id.scrollView) ScrollView scrollView;
#Bind(R.id.toolbar) Toolbar toolbar;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
#Override
public void onScrollChanged() {
float alpha = (float) scrollView.getScrollY() / vehicleDetailsTopLayout.getHeight();
toolbar.setBackgroundColor(getColorWithAlpha(alpha, getResources().getColor(R.color.white)));
toolbar.setTitleTextColor(getColorWithAlpha(alpha, getResources().getColor(R.color.dark_grey)));
}
});
}
public static int getColorWithAlpha(float alpha, int baseColor) {
int a = Math.min(255, Math.max(0, (int) (alpha * 255))) << 24;
int rgb = 0x00ffffff & baseColor;
return a + rgb;
}
}
Problem
However, even if the previous snippets are a particularly simple solution that seems to work perfectly, I am just a little confused about why it didn't work with CoordinatorLayout. Also, I found a guy who seems to have succeed on this task with a custom CoordinatorLayout.Behavior<android.support.v7.widget.Toolbar> implementation.
You can take a look at his custom CoordinatorLayout.Behavior implementation. He also gives some details on Medium. However, due to a lot of just <android.support.v7.widget.Toolbar .../> instead of the full Toolbar tag and a strong lack of understanding of how this part of the Support Design library works, I was never able to implement it...
Question
I would like to understand how CoordinatorLayout, and all the classes around it, works together. So I will probably be able to implement the behavior I am looking for, which is : linking a ScrollView scroll position to the alpha value of a toolbar background color.
Obviously, if you also know how to implement all this, I will be really happy to see your snippet :)
I've been experimenting with behaviors, I am happy you found my article partially helpful.
I redacted the code of the Toolbar chunk because it wasn't important. Simple Toolbar attributes, nothing special about it:
<android.support.v7.widget.Toolbar
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"
android:id="#+id/toolbar"
app:layout_behavior=".view.ToolbarBackgroundAlphaBehavior"/>
I would like to understand how CoordinatorLayout, and all the classes
around it, works together. So I will probably be able to implement the
behavior I am looking for, which is : linking a ScrollView scroll
position to the alpha value of a toolbar background color.
In your layout you are missing the CoordinatorLayout as being top parent that wraps everything. Instead of using ScrollView you should use NestedScrollView it works just like ScrollView but the difference is that NestedScrollView can perform nested scrolls in older version, unlike ScrollView which nested scrolls only after API 23.
For a CoordinatorLayout.Behavior to work the target view must be direct descendant of the CoordinatorLayout. As you can see in the article, the Toolbar is direct descendant of the coordinator. Otherwise, the behavior will not work.
In the example NestedScrollView has appbar layout behavior, so that AppBarLayout can expand and collapse, you can find plenty of examples about this.

What is layout_collapseParallaxMultiplier used in CollapsingToolbarLayout?

What is layout_collapseParallaxMultiplier used in CollapsingToolbarLayout ?
I have seen the android developer doc, but I didn't understand.
please explain this parameter & it's effect when it used with layout_collapseMode with example.
Below is a simple example of xml.
<android.support.design.widget.CollapsingToolbarLayout ... >
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:src="#drawable/random_pattern"
android:scaleType="fitXY"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="0.75"/>
</android.support.design.widget.CollapsingToolbarLayout>
In very simple words:
When scrolling we see the following - appbar image starts hiding under the content and beyond the top edge of the screen.
Parameter layout_collapseParallaxMultiplier determines what part of the image (in percent) will be hidden under the bottom content.
So, for example, setting this parameter to value 1.0 means that top boundary of appbar's image is bound to the top edge of the screen and doesn't move when scrolling. And main content is moving up the top of the image.
When the parameter is not set this corresponds to the value 0.5 and image will be overlapped above and below synchronously.
This was explained on Android Design Support Library:
In addition to pinning a view, you can use app:layout_collapseMode="parallax" (and optionally app:layout_collapseParallaxMultiplier="0.7" to set the parallax multiplier) to implement parallax scrolling (say of a sibling ImageView within the CollapsingToolbarLayout). This use case pairs nicely with the app:contentScrim="?attr/colorPrimary" attribute for CollapsingToolbarLayout, adding a full bleed scrim when the view is collapsed.
This is a behavior example when you use app:layout_collapseMode="parallax".

How does the Android L contacts app collapse its toolbar?

I've been trying to reproduce the way that the Contacts app on version 5.0 collapses the toolbar when the listview is scrolled.
Gallery of screenshots demonstrating the desired interaction
Note the collapse of the toolbar in stages, where it displays search+last contact, fades last contact, collapses last contact, collapses search, leaving only the tabs.
So far, I have a toolbar sitting above a recyclerview in a LinearLayout, and the toolbar is used as an actionbar, not standalone.
I can't figure out how to intercept the touch event on the recyclerview and make it shrink the toolbar, and then return the scroll event to the recyclerview. I tried putting the entire thing in a scrollview, but then the recyclerview couldn't calculate it's height properly and displayed no content. I tried overriding onscroll on the recyclerview, and found that it will only notify me when a scroll event started, and provide me with the first visible card id.
The way that looks right, but I can't get working for the life of me, is this:
getSupportActionBar().setHideOnContentScrollEnabled(true);
Which returns:
Caused by: java.lang.UnsupportedOperationException: Hide on content scroll is not supported in this action bar configuration.
Using a traditional actionbar, putting a toolbar below it, and setting hideoncontentscrollenabled also didn't work, scrolling never triggered the hide method on the actionbar.
-- edit --
I was able to get hideOnContentScrollEnabled working on a listview with a traditional actionbar, but the behavior is not the same as the contacts app. This is clearly not the method they used-- it simply triggers .hide() on the actionbar when a fling event occurs on a listview, which is notably different from the contacts app, which drags the toolbar along with the scroll event.
-- /edit --
So I abandoned that route, and put fill_parent on the cardview height, and animated a collapse on the toolbar. But how do I trigger it so that it follows the touch event and then returns the touch event to the recyclerview?
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/actionBarSize"
android:background="#color/colorPrimary"
/>
<fragment android:name="me.myapplication.FragmentTab"
android:id="#+id/tab_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
fragment_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="8dp"
android:background="#eeeeee"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
styles.xml
...
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
...
MainActivity.java
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
// Disable the logo in the actionbar, as per material guidelines
toolbar.getMenu().clear();
toolbar.setTitle("My toolbar");
setSupportActionBar(toolbar);
I haven't investigated the source code yet but this guy seems to have made life easy yet enlightening.
https://github.com/ksoichiro/Android-ObservableScrollView
EDIT
Google has just released Android Design Library. Please take a look as it contains all the effects of collapsing toolbars and much more.
Well, I have no idea how they do it, but... why don't you take a peek to the source code? Luckily for us, the Contacts app is still open-source on Android L (others weren't as lucky as Contacts, like Mail, which does not work anymore on L; or Keyboard, which they stopped updating anymore since the launch of their propietary Google Keyboard).
Anyway, here's the source code I think you should look at:
https://github.com/android/platform_packages_apps_contacts/blob/master/src%2Fcom%2Fandroid%2Fcontacts%2Factivities%2FActionBarAdapter.java
Note the method update(boolean skipAnimation) in Line 311, which calls animateTabHeightChange(int start, int end) (Line 437).
My guess is all the magic happens there ;-)
As of June 2015, your desired effect can be accomplished via the so called CollapsingToolbarLayout of the new design support library.
Based on the sample code here, I am figuring that:
the search cardview is child of the toolbar
the missed call cardview belongs to the collapsingtoolbar with the collapseMode attribute set to pin
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="112dp"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minHeight="?attr/actionBarSize"
android:fitsSystemWindows="true"
app:layout_scrollFlags="scroll|enterAlwaysCollapsed|enterAlways">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:fitsSystemWindows="false"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:layout_collapseMode="pin"
app:layout_scrollFlags="scroll|enterAlways">
<!-- Search layout -->
<android.support.v7.widget.CardView
</android.support.v7.widget.CardView>
</android.support.v7.widget.Toolbar>
<!-- Last call card view-->
<android.support.v7.widget.CardView
app:layout_collapseMode="pin">
</android.support.v7.widget.CardView>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="#color/primary_color"
app:layout_scrollFlags="scroll"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
No third party library is required now! Android is officially providing library. You can collapse the toolbar and do many other tweaks.
Check this android-developer's blog
And don't forget to add this dependency in your build.gradle file.
compile 'com.android.support:design:22.2.0'
I found this library that seems to do what you're looking for: https://github.com/kmshack/Android-ParallaxHeaderViewPager and this https://github.com/flavienlaurent/NotBoringActionBar
You can play the video to see the behavior: https://www.youtube.com/watch?v=sCP-b0a1x5Y
It might not be the 'new' standard way of doing it with ToolBar, but it might give you an idea by inspecting the code. It seems to attach a OnScrollListener to the scrolling content and then trigger changes on the size of the bar.
For me https://mzgreen.github.io/2015/06/23/How-to-hideshow-Toolbar-when-list-is-scrolling%28part3%29/ has helped. A source code is found here: https://github.com/mzgreen/HideOnScrollExample/tree/master/app/src/main.
A RecycleView in your layout should look like:
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="fill_vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
Note that after starting an application 2 toolbars appear (actionbar and toolbar). So in your activity.java you should write so:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide ActionBar.
supportRequestWindowFeature(WindowCompat.FEATURE_ACTION_BAR);
getSupportActionBar().hide();
setContentView(R.layout.your_activity_layout);
...
The toolbar is customized as shown here: https://stackoverflow.com/a/26548766/2914140. I mean, it appears without title and any other elements, so you can add them in a layout.
Android's Contact app doesn't have an easy plug-and-play solution that you can grab for use in your own app.
It does a full implementation, essentially doing it the same way you would do it if you were implementing it from scratch. For context, before looking at the code, keep in mind how the views are laid out:
https://github.com/android/platform_packages_apps_contacts/blob/lollipop-release/res/layout/quickcontact_activity.xml
The MultiShrinkScroller is a FrameLayout which intermediates the scrolling behavior, but the main stuff is in a LinearLayout, so reducing the height of the higher views will "scroll" the lower views upwards.
The key file for the implementation is this one:
https://github.com/android/platform_packages_apps_contacts/blob/lollipop-release/src/com/android/contacts/widget/MultiShrinkScroller.java
public void scrollTo(int x, int y) {
final int delta = y - getScroll();
boolean wasFullscreen = getScrollNeededToBeFullScreen() <= 0;
if (delta > 0) {
scrollUp(delta);
} else {
scrollDown(delta);
}
updatePhotoTintAndDropShadow();
updateHeaderTextSizeAndMargin();
//... other stuff
}
private void scrollUp(int delta) {
// Collapse higher views first
if (getTransparentViewHeight() != 0) {
final int originalValue = getTransparentViewHeight();
setTransparentViewHeight(getTransparentViewHeight() - delta);
setTransparentViewHeight(Math.max(0, getTransparentViewHeight()));
delta -= originalValue - getTransparentViewHeight();
}
// Shrink toolbar as needed
final ViewGroup.LayoutParams toolbarLayoutParams
= mToolbar.getLayoutParams();
if (toolbarLayoutParams.height > getFullyCompressedHeaderHeight()) {
final int originalValue = toolbarLayoutParams.height;
toolbarLayoutParams.height -= delta;
toolbarLayoutParams.height = Math.max(toolbarLayoutParams.height,
getFullyCompressedHeaderHeight());
mToolbar.setLayoutParams(toolbarLayoutParams);
delta -= originalValue - toolbarLayoutParams.height;
}
// Finally, scroll content if nothing left to shrink
mScrollView.scrollBy(0, delta);
}
updatePhotoTintAndDropShadow(); and updateHeaderTextSizeAndMargin(); handle the change in tint and text as it gets collapsed so that it turns into the look and feel of a regular ActionBar/ToolBar.
You could grab the MultiShrinkScroller file itself and adapt it for your own use, but there are probably easier implementations nowadays (including those from Android's design library).

Categories

Resources