Hiding Scrolling activity title in android studio - android

I have created a Scrolling activity.
I want to hide this activity title (Banglalink Latest Offers).
But
I want to show activity title at this stage (Banglalink Latest Offers).
Is it possible to do?
If yes, how?

A bit late but I think this might help someone looking for a solution for this, you can simply set the text color to transparent.
Just add the below style to your styles.xml:
<style name="ToolBarTheme">
<item name="android:textColor">#android:color/transparent</item>
</style>
and add the following attribute to your CollapsingToolbarLayout:
app:expandedTitleTextAppearance="#style/ToolBarTheme"

Simply add this line to CollapsingToolbarLayout in your xml file:
app:titleEnabled="false"

Your best bet it to convert to a normal activity (with a scrollview as a child), start with the actionbar hidden (using the hide() call below (put it inside onCreate()).
Then put the coloured backgroiund at top of screen inside scrollview.
Finally, you can programmatically toggle between hiding your title (and actionbar), but showing your header background (or vice versa) when needed by adding a horizontal scroll listener/observer.
The listener will toggle the actionbar and header view depending on how far the user has scrolled down.
E.g:
Add observer inside onStart():
hsv.getViewTreeObserver().addOnScrollChangedListener(
new ViewTreeObserver.OnScrollChangedListener()
{ #Override public void onScrollChanged()
{
Log.i(TAG,"scroll:"+hsv.getScrollX());}});
// todo adjust scrollx value to decide on hide or show call:
if (hsv.getScrollX() > 100)
getActionBar().show();
mHeaderLayoutView.setVisibility(View.GONE);
else
getActionBar().hide();
mHeaderLayoutView.setVisibily(View.VISIBLE)
...
Note: hsv is a HorizontalScrollView works.
Note, if your are using the support libraries (E.g. you activity class extends AppCompatActivity), the code would change to:
getSupportActionBar().hide();
Im not sure if the getScrollX is in pixels or dp (job for you to research).
Hope this helps!

<resources>
<dimen name="app_bar_height">180dp</dimen>
<dimen name="fab_margin">16dp</dimen>
<dimen name="text_margin">16dp</dimen>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="appbar_padding_top">8dp</dimen>
</resources>
This must be your dimens.xml file. If you reduce the app_bar_height to 120dp or close... the text will be invisible. I dont know how to bring it back after collapse

This is working for me:
CollapsingToolbarLayout toolbarLayout = (CollapsingToolbarLayout)
findViewById(R.id.toolbar_layout);
toolbarLayout.setTitle(" ");

You have to remove the line android:theme="#style/AppTheme.AppBarOverlay"in your XML. Once you removed the title will go to background. So you able hide title of the activity. as an example, you can place a placeholder to hide it.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="220dp"
android:fitsSystemWindows="true"
>
<!--android:theme="#style/AppTheme.AppBarOverlay"-->
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:toolbarId="#+id/toolbar">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
app:layout_collapseMode="pin"
app:srcCompat="#drawable/place_holder" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="6dp"
android:layout_marginStart="6dp"
android:layout_marginTop="8dp"
android:src="#mipmap/next"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/AppTheme.PopupOverlay"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_display_shop" />
</android.support.design.widget.CoordinatorLayout>

you can use supportActionBar and change title with "" (string null)
setSupportActionBar(findViewById(R.id.toolbar))
findViewById<CollapsingToolbarLayout>(R.id.toolbar_layout).title = title
supportActionBar!!.title=""
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
or you can change in findViewById
findViewById<CollapsingToolbarLayout>(R.id.toolbar_layout).title = title

Calling this method from onCreate()
initCollapsingToolbar();
Defining the method
private void initCollapsingToolbar() {
final CollapsingToolbarLayout collapsingToolbar =
(CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
collapsingToolbar.setTitle(" ");
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.app_bar);
appBarLayout.setExpanded(true);
// hiding & showing the title when toolbar expanded & collapsed
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
collapsingToolbar.setTitle("Your app title");
isShow = true;
} else if (isShow) {
collapsingToolbar.setTitle(" ");
isShow = false;
}
}
});
}

Related

Using CollapsingToolbarLayout without setSupportActionBar cause wrong collapsed title position

Like the title said, if using toolbar without setSupportActionBar in activity, when the toolbar is collapsed, the title of toolbar will have a strange top padding, and this padding is 24dp height, which is the height of the statusbar.
The screenshot:
But if I add setSupportActionBar(toolbar) to Activity's onCreate, then this problem resolved.
The layout file is as follows:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
android:fitsSystemWindows="true"
tools:context=".ScrollingActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="#dimen/app_bar_height"
android:fitsSystemWindows="true"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:toolbarId="#+id/toolbar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
app:title="test"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_scrolling" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/fab_margin"
app:layout_anchor="#id/app_bar"
app:layout_anchorGravity="bottom|end"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
I'm just using the sample ScrollActivity without big modification, just add a app:title to Toolbar, and comment out setSupportActionBar(toolbar);
the version of design library is 27.1.1
In fact, I worked out this problem but just don't get the reason why Google do this.
In the onLayout method of CollapsingToolbarLayout, it will first calculate toolbar's collapsed title's position
final int maxOffset = getMaxOffsetForPinChild(
mToolbarDirectChild != null ? mToolbarDirectChild : mToolbar);
ViewGroupUtils.getDescendantRect(this, mDummyView, mTmpRect);
mCollapsingTextHelper.setCollapsedBounds(
mTmpRect.left + (isRtl
? mToolbar.getTitleMarginEnd()
: mToolbar.getTitleMarginStart()),
mTmpRect.top + maxOffset + mToolbar.getTitleMarginTop(),
mTmpRect.right + (isRtl
? mToolbar.getTitleMarginStart()
: mToolbar.getTitleMarginEnd()),
mTmpRect.bottom + maxOffset - mToolbar.getTitleMarginBottom());
and the maxOffset is calculated at getMaxOffsetForPinChild, which is as follows:
final int getMaxOffsetForPinChild(View child) {
final ViewOffsetHelper offsetHelper = getViewOffsetHelper(child);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
return getHeight()
- offsetHelper.getLayoutTop()
- child.getHeight()
- lp.bottomMargin;
}
the problem is, offsetHelper.getLayoutTop() will first returns 0 instead of the real top 24dp, because at this time, offsetHelper's onViewLayout has not got called, it will be called after calculating collapsed title position.
// Update our child view offset helpers. This needs to be done after the title has been
// setup, so that any Toolbars are in their original position
for (int i = 0, z = getChildCount(); i < z; i++) {
getViewOffsetHelper(getChildAt(i)).onViewLayout();
}
and according to the comment, this is the intend behavior, onViewLayout must be called after the title has been setup.This is the point I don't get.
I guess setSupportActionBar did something make onLayout get called again, which will recalculate the title's position with the right LayoutTop. So I add the following code:
final CollapsingToolbarLayout v = findViewById(R.id.toolbar_layout);
v.post(new Runnable() {
#Override
public void run() {
v.requestLayout();
}
});
to the activity's onCreate method, and problem solved.
Now, I'll leave this question open since I don't think this is a elegant solution and maybe there is some offical method to solve this problem. Or is this a bug Android dev don't aware?

How to determine if an ImageView is visible in CollapsingToolbar?

I have a collapsing toolbar layout that looks like this:
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="#dimen/expanded_toolbar_height"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<include layout="#layout/circle_image_view"/>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.CollapsingToolbarLayout>
where circle_image_view is
<com.example.ui.CircularParseImageView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/iv_circular_backdrop"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_gravity="center"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
android:transitionName="#string/transition_pic"
app:layout_collapseMode="parallax" />
This is just a standard image view with a circular mask. When the the collapsing toolbar is expanded, the circular Image view is visible and shows like:
When collapsed, the image view is no longer visible as follows:
However it seems like the visibility of the image view is still set to Visible even in the collapsed state. When the user presses the back button, I need to determine whether the image is visible or not to perform a shared element transition animation. How can I determine if the image is currently visible or not within the collapsing toolbar?
What I have tried:
getVisibility() remains unchanged
isOpaque() remains unchanged
getImageAlpha() remains unchanged
I was able to resolve the issue by using CollapsingToolbarLayout#getContentScrim() which according to documentation:
Returns the drawable which is used for the foreground scrim.
Seems like the image view is always visible but the foreground scrim hides it so using the alpha property getContentScrim().getAlpha() you can determine whether the image is visible or not.
this can be achieved using your own implementation of a OnOffsetChangedListener.
AppBarLayout appBarLayout = (AppBarLayout) view.findViewById(R.id.app_bar_layout);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (Math.abs(verticalOffset) == appBarLayout.getTotalScrollRange()) {
// Collapsed
} else if (verticalOffset == 0) {
// Expanded
} else {
// Somewhere in between
}
}
}););
mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
boolean isContentHide = mCollapsingToolbarLayout.getScrimVisibleHeightTrigger() + Math.abs(verticalOffset) > mCollapsingToolbarLayout.getHeight();
}
});

CollapsingToolbarLayout arrow color

I'm using CollapsingToolbarLayout in my Activity, but I need to change color of back arrow when it is expanded, is there any way to do this?
What I have:
What I want to do:
Here is my layout, where i put "..." there is layout include with NestedScrollView in it.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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"
android:fitsSystemWindows="true"
tools:context="com.primebitstudio.swiper.AboutCouponActivity"
android:layout_marginTop="-1px">
<android.support.design.widget.AppBarLayout android:id="#+id/app_bar"
android:fitsSystemWindows="true"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout android:id="#+id/toolbar_layout"
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleTextAppearance="#style/CollapsingToolbarLayoutExpandedTextStyle"
app:theme="#style/ThemeOverlay.AppCompat.Light"
app:popupTheme="#style/ToolBarStyle">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-24dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="#drawable/test_image"
android:id="#+id/image"/>
</RelativeLayout>
<android.support.v7.widget.Toolbar android:id="#+id/toolbar"
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"
app:layout_collapseMode="pin"
app:popupTheme="#style/ToolBarStyle" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
...
...
</android.support.design.widget.CoordinatorLayout>
Here is the example how I change my drawer and options icons color when layout is expanded and collapsed:
protected void onCreate(Bundle savedInstanceState) {
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.app_bar_layout);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int offset)
{
Drawable upArrow = ResourcesCompat.getDrawable(getResources(), R.drawable.drawer_icon, null);
if (offset < -200)
{
upArrow.setColorFilter(Color.parseColor("#000000"), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),R.drawable.option_menu_icon);
drawable.setColorFilter(Color.parseColor("#000000"), PorterDuff.Mode.SRC_ATOP);
toolbar.setOverflowIcon(drawable);
}
else
{
upArrow.setColorFilter(Color.parseColor("#ffffff"), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),R.drawable.option_menu_icon);
drawable.setColorFilter(Color.parseColor("#ffffff"), PorterDuff.Mode.SRC_ATOP);
toolbar.setOverflowIcon(drawable);
}
}
});
From the documentation on ActionBarDrawerToggle:
You can customize the the animated toggle by defining the drawerArrowStyle in your ActionBar theme.
The drawerArrowStyle attribute lists the following attributes that can be configured:
android.support.v7.appcompat:arrowHeadLength
The length of the arrow head when formed to make an arrow
android.support.v7.appcompat:arrowShaftLength
The length of the shaft when formed to make an arrow
android.support.v7.appcompat:barLength
The length of the bars when they are parallel to each other
android.support.v7.appcompat:color
The drawing color for the bars
android.support.v7.appcompat:drawableSize
The total size of the drawable
android.support.v7.appcompat:gapBetweenBars
The max gap between the bars when they are parallel to each other
android.support.v7.appcompat:spinBars
Whether bars should rotate or not during transition
android.support.v7.appcompat:thickness
The thickness (stroke size) for the bar paint
I reckon android.support.v7.appcompat:color is what you're after.
In order to change the colour at runtime, you have multiple options.
Option 1
Get the navigation icon from your Toolbar and apply a colour filter to it. For example, to colour the icon red, one could do something like this:
Drawable navIcon = mToolbar.getNavigationIcon();
navIcon.setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
The advantage of this approach is that you can play around with the various PorterDuff.Mode constants to achieve different effects. This approach will also work (and keep working) if you decide to supply your own navigation icon (instead of the default hamburger-turns-arrow-and-vice-versa drawable).
Option 2
If you're only interested in colouring the default navigation icon, you can leverage the fact that the navigation icon drawable is a DrawerArrowDrawable, which has a setColor() method:
DrawerArrowDrawable navIcon = (DrawerArrowDrawable) mToolbar.getNavigationIcon();
navIcon.setColor(Color.RED);
This second approach may be easier to use if you're planning on animating the colour gradually with the help of i.e. ObjectAnimator.ofArgb(...) or ValueAnimator.ofArgb(...) (rather than just setting it).
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
int scrollRange = -1;
#Override
public void onOffsetChanged(final AppBarLayout appBarLayout, int verticalOffset) {
//Initialize the size of the scroll
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
//Check if the view is collapsed
if (scrollRange + verticalOffset == 0) {
#SuppressLint("UseCompatLoadingForDrawables") final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
upArrow.setColorFilter(getResources().getColor(R.color.black), PorterDuff.Mode.SRC_ATOP);
Objects.requireNonNull(getSupportActionBar()).setHomeAsUpIndicator(upArrow);
} else {
#SuppressLint("UseCompatLoadingForDrawables") final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
upArrow.setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
Objects.requireNonNull(getSupportActionBar()).setHomeAsUpIndicator(upArrow);
}
}
});
if you want to change the color of the back-button of the toolbar when using collapsingtoolbarlayout in android.
this is the condition when you want to show different color of back-button when appbarlayout is collapsed or when it is expanded.

Hiding AppBarLayout and giving its space to the remaining view

I have a pretty standard layout using the new design libraries:
<AppBarLayout>
<CollapsingToolbarLayout>
<ImageView/>
<Toolbar/>
</CollapsingToolbarLayout>
</AppBarLayout>
<android.support.v4.widget.NestedScrollView/> <!-- content here -->
What I'm trying to do is to completely hide the whole AppBarLayout programmatically, to temporarily get rid of the Toolbar and its collapsing feature.
So I'm calling this:
private void disableCollapsing() {
AppBarLayout.LayoutParams p = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams();
p.setScrollFlags(0);
collapsingToolbarLayout.setLayoutParams(p);
}
to disable the collapsing behavior (works well), and finally this:
#Override
public void hide() {
final AppBarLayout layout = (AppBarLayout) findViewById(R.id.appbar);
layout.animate().translationY(-layout.getHeight())
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
layout.setVisibility(View.GONE);
}
}).start();
}
I make the AppBarLayout translate to the top (works smoothly), and at the end of the animation set is visibility to View.GONE.
Issue
At the end of the animation, no matter I also set the visibility to GONE, I can't get the space that was previously occupied by the AppBarLayout. My NestedScrollView remains confined in the lower half of the screen, as if the AppBarLayout was still there (which is not). How can I fix it?
Before hiding:
After hiding (AppBar translated to the top):
As you can see, the top space is empty and unreachable. The scroll view scrolls inside the margins it had before, as if the visibility change was not measured by the CoordinatorLayout.
I have tried calling coordinator.requestLayout(), with no success.
I also tried setting the AppBarLayout as an app:anchor for my NestedScrollView, but that screws things up - scroll view ends up taking the whole screen even before hiding.
I was thinking of a custom Behavior to be set on the scroll view when entering this hidden-AppBar mode, but I can't get started on that.
Yes this looks like a bug, I solved this issue for my application setting the appbar height to 0:
android.support.design.widget.AppBarLayout appbar = (android.support.design.widget.AppBarLayout) findViewById(R.id.appbar);
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams)appbar.getLayoutParams();
lp.height = 0;
appbar.setLayoutParams(lp);
As mentioned above, setting the Coordinator.LayoutParams#height fixes the issue.
However, I wanted to express how/when this occurs (not necessarily why):
The CollaspingToolbarLayout will exhibit this behavior only when its app:layout_scrollFlags property is set to exitUntilCollapsed and its nested ToolBar also has defines app:layout_collapseMode="pin". With this combination of flags, the Toolbar will pin itself to the top of the screen, and this is intentional and sometimes desirable.
(snipped for brevity)
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="#+id/collapsingToolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<!-- some other component here, i.e ImageView -->
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:gravity="top"
app:layout_collapseMode="pin" />
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<!-- some scrolling view/layout -->
</androidx.coordinatorlayout.widget.CoordinatorLayout>
In the Fragment/Activity after the view is created, in Kotlin + ViewBinding:
binding.appbar.updateLayoutParams<CoordinatorLayout.LayoutParams> {
height = 0
}
For me, I had to capture the height of the AppBarLayout before hiding it to restore it to its original height when I wanted to show it.
private var appbarLayoutHeight = 0
private fun hideAppBar() {
appbarLayoutHeight = binding.appbar.measuredHeight
binding.appbar.updateLayoutParams<CoordinatorLayout.LayoutParams> {
height = 0
}
}
private fun showAppBar() {
binding.appbar.updateLayoutParams<CoordinatorLayout.LayoutParams> {
height = appbarLayoutHeight
}
}
Disclaimer: ViewBinding is not necessary to achieve this, nor is using Kotlin, and it's just what I use to acquire the AppBarLayoout and make this as terse/sugary as possible.
This works for me. Just toggles appbar on/off.
private boolean hide = true;
public void toggleAppBar() {
// Calculate ActionBar height
TypedValue tv = new TypedValue();
int actionBarHeight = 0;
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
}
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams)appBarLayout.getLayoutParams();
lp.height = hide ? 0 : actionBarHeight;
appBarLayout.setLayoutParams(lp);
appBarLayout.setExpanded(!hide, true);
hide = !hide;
appbar_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<include layout="#layout/content_main" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Thanks #Caleb Kleveter that is my code for Kotlin
val appBarLayout = activity?.findViewById<AppBarLayout>(R.id.app_bar_layout)
val lp = appBarLayout?.layoutParams
lp?.height = 0;
appBarLayout?.layoutParams = lp
The following works as well
appBarLayout.setExpanded(false, false);
appBarLayout.setVisibility(View.GONE);

Android Material Design - How to change background color of Toolbar after CollapsingToolbarLayout is collapsed

After the user scrolls down the screen, the image in the CollapsingToolbarLayout disappears and is left with a toolbar with the back button, content title, and settings menu. I want to know how to change the background color of that toolbar only when its in a 'collapsed' state.
The action I am referring to is similar to this where the toolbar background color changes to green:
Below the CollapsingToolbarLayout I have a NestedScrollView with CardViews
I think you're after app:contentScrim.
<android.support.design.widget.CollapsingToolbarLayout
...
app:contentScrim="?attr/colorPrimary">
<!-- Toolbar and ImageView here -->
</android.support.design.widget.CollapsingToolbarLayout>
First remove
app:contentScrim="?attr/colorPrimary">
from CollapsingToolbarLayout
Add library
compile 'com.android.support:palette-v7:23.2.1'
And add below code in java code
Bitmap bitmap = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.ny);
Palette.generateAsync(bitmap,
new Palette.PaletteAsyncListener() {
#Override
public void onGenerated(Palette palette) {
Palette.Swatch vibrant =
palette.getVibrantSwatch();
int mutedColor = palette.getVibrantSwatch().getRgb();
if (vibrant != null) {
// If we have a vibrant color
// update the title TextView
collapseToolbar.setBackgroundColor(mutedColor);
// mutedColor = palette.getMutedColor(R.attr.colorPrimary);
collapseToolbar.setStatusBarScrimColor(palette.getDarkMutedColor(mutedColor));
collapseToolbar.setContentScrimColor(palette.getMutedColor(mutedColor));
}
}
});
Just use CollapsingToolbarLayout XML attribute contentScrim to set Toolbar background color when it's in collapsed mode.
app:contentScrim="YOUR_TOOLBAR_COLOR"
Here is an Example:
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="#+id/img_group_photo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
app:layout_collapseMode="parallax" />
<android.support.v7.widget.Toolbar
android:id="#+id/anim_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.CollapsingToolbarLayout>
Hope this will help~
Maybe what you have been looking for is this :
myCollapsingToolbar.setContentScrimColor(getResources().getColor(R.color.my_color_id));
It worked for me and changed the color of the collapsingToolbar once it was collapsed to help me fit the main color of an image that was displayed when the collapsingToolbar was full scale. With this, the color can obviously be changed programatically!
I know I'm late, but I hope it could help.
You can use an AppBarLayout's offset listener and change the CollapsingTollbar attributes according to the desired behavior.
appBarLayout.addOnOffsetChangedListener { _, verticalOffSet ->
if (Math.abs(verticalOffSet) == appBarLayout.totalScrollRange) {
//Collapsed
toolBar.setBackgroundDrawable(ContextCompat.getDrawable(this,
R.drawable.last_revolut_gradient))
} else {
//Expanded
toolBar.setBackgroundColor(ContextCompat.getColor(this,
android.R.color.transparent))
}
}
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.header);
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
#SuppressWarnings("ResourceType")
#Override
public void onGenerated(Palette palette) {
Palette.Swatch vibrant =
palette.getVibrantSwatch();
if (vibrant != null) {
collapsingToolbar.setBackgroundColor(getResources().getColor(R.color.cpb_blue));
collapsingToolbar.setStatusBarScrimColor(getResources().getColor(R.color.cpb_blue));
collapsingToolbar.setContentScrimColor(getResources().getColor(R.color.cpb_blue));
}
}
});

Categories

Resources