I have a collapsing toolbar layout which contains an image and on collapse shows the toolbar title. I needed to change the toolbar title font so I added a textview inside toolbar layout. Now I'm getting the following error generated repeatedly whenever I collapse the toolbar.
08-12 13:14:19.604 2263-2263/com.panoroma.admin W/View: requestLayout() improperly called by android.support.design.widget.CollapsingToolbarLayout{2d353cd6 V.ED.... ........ 0,0-1080,390 #7f0c0070 app:id/collapsing_toolbar} during second layout pass: posting in next frame
08-12 13:14:19.604 2263-2263/com.panoroma.admin W/View: requestLayout() improperly called by android.support.v7.widget.AppCompatTextView{1bb84b57 V.ED.... ........ 168,48-407,119 #7f0c0073 app:id/toolbar_title} during second layout pass: posting in next frame
my layout...
<android.support.design.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">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed|exitUntilCollapsed">
<ImageView
android:id="#+id/header"
android:layout_width="100dp"
android:layout_height="100dp"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:scaleType="centerCrop"
android:layout_marginTop="15dp"
android:layout_marginBottom="15dp"
android:background="#drawable/dashboard80"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="0.5" />
<android.support.v7.widget.Toolbar
android:id="#+id/da_toolbar"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
app:layout_collapseMode="pin"
android:layout_height="?attr/actionBarSize">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="?attr/colorAccent"
android:id="#+id/toolbar_title"/>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/rel_dash_icon"
app:layout_behavior="#string/appbar_scrolling_view_behavior" >
.........................
</ScrollView>
</android.support.design.widget.CoordinatorLayout>
java file..
Typeface ubuntuC = Typeface.createFromAsset(getAssets(), "ubuntuC.ttf");
Toolbar toolbar = (Toolbar) findViewById(R.id.da_toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
toolbar_title = (TextView)toolbar.findViewById(R.id.toolbar_title);
toolbar_title.setTypeface(ubuntuC);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
getSupportActionBar().setHomeAsUpIndicator(getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha, null));
else
getSupportActionBar().setHomeAsUpIndicator(getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
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) {
// collapsingToolbarLayout.setTitle("Dashboard");
toolbar_title.setText("Dashboard");
isShow = true;
} else if(isShow) {
// collapsingToolbarLayout.setTitle("");
toolbar_title.setText("");
isShow = false;
}
}
});
I just want a toolbar with a center image which on collapse will display the title. Title will have custom font. Now, is there a better way doing this?
Following piece of code worked for me
added post Runnable on AppBarLayout
mAppBar.addOnOffsetChangedListener(new AppBarStateChangeListener() {
#Override
public void onStateChanged(AppBarLayout appBarLayout, final int state, int done) {
mAppBar.post(new Runnable() {
#Override
public void run() {
if (state == COLLAPSED) {
mToolBarTitle.setText(model.getTitle());
} else if (state == EXPANDED || state == IDLE) {
mToolBarTitle.setText("");
}
}
});
}
});
onOffsetChanged() is called so many times and android is throwing that warning because you are requesting layout as part of toolbar_title.setText("Dashboard"); . What you should do is , use a boolean flag and call it only once if the condition is met or check the VISIBILITY flag for the toolbar text view ,something like this.
Add textview inside your toolbar layout under CollapsingLayout
< 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">
<TextView
android:id="#+id/toolbar_title"
style="#style/Toolbar.Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_gravity="center" />
</android.support.v7.widget.Toolbar>
In your activity or fragment class inside OnOffsetChangedListener() modify some thing like below with check. This will stop the warnings.
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (verticalOffset == toolbar.getHeight() - collapsingToolbarLayout.getHeight()) {
if (textView.getVisibility() != View.VISIBLE) {
textView.setVisibility(View.VISIBLE);
textView.setText(title); // show toolbar title
}
} else {
if (textView.getVisibility() != View.GONE) {
textView.setVisibility(View.GONE); // hide title bar
}
}
}
});
}
I had the same problem with my onOffsetChangedListener. To fix it, I had to wrap my code a runnable that runs on the UI thread.
So with yours you would have to do the following:
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
collapsingToolbarLayout.setTitle("Dashboard");
toolbar_title.setText("Dashboard");
isShow = true;
} else if(isShow) {
collapsingToolbarLayout.setTitle(" ");
toolbar_title.setText(" ");
isShow = false;
}
}
});
Note the space between the quotation marks in setTitle and setText. I believe you need a space or it won't work. Also, make sure in your xml that you have
app:titleEnabled="false"
on your CollapsingToolbarLayout.
Hope that solved the problem :)
I had the same problem and this page gives me a hint : here
I removed the collapsingToolbarLayout.setTitle("Dashboard"); collapsingToolbarLayout.setTitle(" ");
and created two styles in styles.xml:
<style name="CustomCollapsingCollapsed">
<item name="android:textColor">#color/colorText</item>
</style>
<style name="CustomCollapsingExpanded">
<item name="android:textColor">#color/transparent</item>
</style>
And use them in
<android.support.design.widget.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="#color/colorAccent"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:expandedTitleTextAppearance="#style/CustomCollapsingExpanded"
app:collapsedTitleTextAppearance="#style/CustomCollapsingCollapsed"
>
No logs anymore... Hope it helps!
You can actually set a title colour for collapsed and expanded mode which will transition between the two when the toolbar is collapsing.
In your case rather then manually handling the collapse/expansion and setting the title you could set the expanded title colour to transparent and the collapsed title colour to whatever you originally wanted it to be.
So now when expanded the toolbar title is invisible and when collapsed the toolbar title is visible.
I had the same problem in the implementation of the listener onOffsetChanged.
What I did basically is a flag before assigning the new values. Where once the specific values of the layout parameters are assigned, they are saved and then before being reassigned, they are compared with the old values.
private ConstraintLayout.LayoutParams params;
private float horizontalBias = 0;
private float verticalBias = 0;
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
params = (ConstraintLayout.LayoutParams) mOrderPictureDetail.getLayoutParams();
...
if (params.horizontalBias != horizontalBias && params.verticalBias != verticalBias) {
horizontalBias = params.horizontalBias;
verticalBias = params.verticalBias;
mOrderPictureDetail.setLayoutParams(params);
}
}
GL
Source
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
#Override
public void onOffsetChanged(final AppBarLayout appBarLayout, final int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
if (mToolbarTitle.getVisibility() == View.GONE) {
mToolbarTitle.setVisibility(View.VISIBLE);
mCollapsingToolbarLayout.setTitle("昵称");
mToolbarTitle.setText("昵称");
}
isShow = true;
} else if (isShow) {
mToolbarTitle.setVisibility(View.GONE);
isShow = false;
}
}
});
Hope that solved the problem
Related
I have a View and a RecyclerView housed in a LinearLayout. What I want to achieve is something like this:
https://material.google.com/patterns/scrolling-techniques.html#scrolling-techniques-behavior
Basically when I scroll the RecyclerView up, the View collapses. It expands if I scroll the RecyclerView down.
I've tried various methods but the animation stutters if the finger jerks around a scroll position. It only animates well if the finger does a deliberate scroll movement in one direction. How do I do this correctly?
You have to use Coordinator Layout with the CollapsingToolbarLayout
<android.support.design.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"
android:clipToPadding="false">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="210dp"
android:stateListAnimator="#animator/appbar_always_elevated" //I put this here because I want to have shadow when is open, but you have to create the xml file.
android:background="#color/WHITE">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:collapsedTitleTextAppearance="#style/TextAppearance.AppCompat.Widget.ActionBar.Title.Inverse"
app:expandedTitleMarginStart="72dp"
app:expandedTitleTextAppearance="#style/TextAppearance.AppCompat.Widget.ActionBar.Title.Inverse"
app:layout_scrollFlags="scroll|exitUntilCollapsed"> //HERE you should take a look what you want your collapse bar do.
<Here you put the content for you collapse bar, like a ImageView>
<android.support.v7.widget.Toolbar //This is the size of your fixed bar when you collapse, even here you can put a back button, for example
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="40dp"
app:layout_collapseMode="pin" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/main_home_list_swipe"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" >
<android.support.v7.widget.RecyclerView
android:id="#+id/main_home_list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.design.widget.CoordinatorLayout >
Obs: the comments will give errors if you put on a xml file. Is on propose so you will remember to read hahahah
Try this:-
I also want this kind of animation on custom view and i have achieved it this way.
public class TestActivity extends AppCompatActivity {
private static final int HIDE_THRESHOLD = 20;
//this is you custom layout it is any thing.
LinearLayout customLayout;
private int scrolledDistance = 0;
private boolean controlsVisible = true;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
scrolledDistance = dy;
if (scrolledDistance > HIDE_THRESHOLD && controlsVisible) {
hideViews();
controlsVisible = false;
} else if (scrolledDistance < -HIDE_THRESHOLD && !controlsVisible) {
showViews();
controlsVisible = true;
}
}
});
}
private void hideViews() {
customLayout.animate().translationY(-customLayout.getHeight()).setInterpolator(new AccelerateInterpolator(2));
}
private void showViews() {
customLayout.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2));
}
}
Edit - 1
for ScrollView try this listener
scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
#Override
public void onScrollChanged() {
if (scrolledDistance > HIDE_THRESHOLD && controlsVisible) {
hideViews();
controlsVisible = false;
scrolledDistance = 0;
} else if (scrolledDistance < -HIDE_THRESHOLD && !controlsVisible) {
showViews();
controlsVisible = true;
scrolledDistance = 0;
}
}
});
Hope it also helps you...
To achieve toolbar to expand and collapse smoothly you can apply translate animation or use CoordinatorLayout with AppBarLayout and Toolbar.
Animation : First you have to detect scroll up and scroll down on your RecyclerView. To do so you can set “setOnScrollListener” on your RecyclerView. Once you have both scroll up and scroll down, simply apply animation.
Code:
rvHomeList.setOnScrollListener(new RecyclerView.OnScrollListener() {
int verticalOffset;
boolean scrollingUp;
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
if (scrollingUp) {
Log.e("onScrollStateChanged", "UP");
if (verticalOffset > llTop.getHeight()) {
toolbarAnimateHide();
}
} else {
Log.e("onScrollStateChanged", "down");
if (llTop.getTranslationY() < llTop.getHeight() * -0.6 && verticalOffset > llTop.getHeight()) {
toolbarAnimateHide();
} else {
toolbarAnimateShow(verticalOffset);
}
}
}
}
#Override
public final void onScrolled(RecyclerView recyclerView, int dx, int dy) {
verticalOffset += dy;
scrollingUp = dy > 0;
int toolbarYOffset = (int) (dy - llTop.getTranslationY());
llTop.animate().cancel();
if (scrollingUp) {
Log.e("onScrolled", "UP");
if (toolbarYOffset < llTop.getHeight()) {
llTop.setTranslationY(-toolbarYOffset);
} else {
llTop.setTranslationY(-llTop.getHeight());
}
} else {
Log.e("onScrolled", "down");
if (toolbarYOffset < 0) {
llTop.setTranslationY(0);
} else {
llTop.setTranslationY(-toolbarYOffset);
}
}
}
});
Animation Methods:
private void toolbarAnimateShow(final int verticalOffset) {
if (!isShowing) {
isShowing = true;
llTop.animate()
.translationY(0)
.setInterpolator(new LinearInterpolator())
.setDuration(180)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationStart(Animator animation) {
llTop.setVisibility(View.VISIBLE);
isShowing = false;
}
});
}
}
private void toolbarAnimateHide() {
if (!isHidding) {
isHidding = true;
llTop.animate()
.translationY(-llTop.getHeight())
.setInterpolator(new LinearInterpolator())
.setDuration(180)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
llTop.setVisibility(View.GONE);
isHidding = false;
}
});
}
}
CoordinatorLayout with AppBarLayout and Toolbar: By using coordinatorLayout with appBarLayout and toolbar, and set the scroll flag used within the attribute app:layout_scrollFlags to achieve the scroll effect. It must be enabled for any scroll effects to take into effect. This flag must be enabled along with enterAlways, enterAlwaysCollapsed, exitUntilCollapsed, or snap.
enterAlways: The view will become visible when scrolling up. This flag is useful in cases when scrolling from the bottom of a list and wanting to expose the Toolbar as soon as scrolling up takes place.
enterAlwaysCollapsed: Normally, when only enterAlways is used, the Toolbar will continue to expand as you scroll down.Assuming enterAlways is declared and you have specified a minHeight, you can also specify enterAlwaysCollapsed. When this setting is used, your view will only appear at this minimum height. Only when scrolling reaches to the top will the view expand to its full height
exitUntilCollapsed: When the scroll flag is set, scrolling down will normally cause the entire content to move.By specifying a minHeight and exitUntilCollapsed, the minimum height of the Toolbar will be reached before the rest of the content begins to scroll and exit from the screen
snap: Using this option will determine what to do when a view only has been partially reduced. If scrolling ends and the view size has been reduced to less than 50% of its original, then this view to return to its original size. If the size is greater than 50% of its sized, it will disappear completely.
Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/llBase"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:orientation="vertical">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbarContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="#dimen/_40sdp"
android:gravity="center"
android:theme="#style/ThemeOverlay.AppCompat.Light"
app:layout_scrollFlags="scroll|enterAlways">
<include
layout="#layout/top_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<RelativeLayout
android:id="#+id/rlMain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
</LinearLayout>
You need to use CoordinatorLayout to achieve what you want.
You could find all needed information in this tutorial.
I am trying to achieve a similar behavior to that of Telegram, on the settings page, that is, there is a CircleImage that when scrolling up goes to the left of the Topbar title, and when scrolling down goes to the middle of the expanded AppBarLayout.
I was basing my work on this example:
https://github.com/saulmm/CoordinatorBehaviorExample
But in this case the original coder is recreating the Topbar twice. I dont want to do that, the default behavior of the topbar is what I need and also I want to take advantage of the hamburger menu and the options menu that come out of the box.
This is my view hierarchy:
DrawerLayout
|
|---CoordinatorLayout
|--AppBarLayout
| |-CollapsingToolbarLayout
| |-ImageView (backdrop image)
| |-Toolbar
|--NestedScrollView
|--ImageView (circleimage avatar)
As you can see I cannot make the Toolbar layout a sibling of my CircleImage so I cannot bind them together on the layoutDependsOn method. I tried binding to the AppBarLayout basing my code off the one on the github repo but to be honest I cannot make much sense of what's happening in the original code.
My behavior was implemented in much the same manner as Saul's. The biggest difference is that I like to put a non-visible view like a Space where I wanted the circle image to end up, then use that view's bounds to determine how to move & size the circle image.
public class CollapsingImageBehavior extends CoordinatorLayout.Behavior<View> {
private final static int X = 0;
private final static int Y = 1;
private final static int WIDTH = 2;
private final static int HEIGHT = 3;
private int mTargetId;
private int[] mView;
private int[] mTarget;
public CollapsingImageBehavior() {
}
public CollapsingImageBehavior(Context context, AttributeSet attrs) {
if (attrs != null) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CollapsingImageBehavior);
mTargetId = a.getResourceId(R.styleable.CollapsingImageBehavior_collapsedTarget, 0);
a.recycle();
}
if (mTargetId == 0) {
throw new IllegalStateException("collapsedTarget attribute not specified on view for behavior");
}
}
#Override
public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
return dependency instanceof AppBarLayout;
}
#Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
setup(parent, child);
AppBarLayout appBarLayout = (AppBarLayout) dependency;
int range = appBarLayout.getTotalScrollRange();
float factor = -appBarLayout.getY() / range;
int left = mView[X] + (int) (factor * (mTarget[X] - mView[X]));
int top = mView[Y] + (int) (factor * (mTarget[Y] - mView[Y]));
int width = mView[WIDTH] + (int) (factor * (mTarget[WIDTH] - mView[WIDTH]));
int height = mView[HEIGHT] + (int) (factor * (mTarget[HEIGHT] - mView[HEIGHT]));
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) child.getLayoutParams();
lp.width = width;
lp.height = height;
child.setLayoutParams(lp);
child.setX(left);
child.setY(top);
return true;
}
private void setup(CoordinatorLayout parent, View child) {
if (mView != null) return;
mView = new int[4];
mTarget = new int[4];
mView[X] = (int) child.getX();
mView[Y] = (int) child.getY();
mView[WIDTH] = child.getWidth();
mView[HEIGHT] = child.getHeight();
View target = parent.findViewById(mTargetId);
if (target == null) {
throw new IllegalStateException("target view not found");
}
mTarget[WIDTH] += target.getWidth();
mTarget[HEIGHT] += target.getHeight();
View view = target;
while (view != parent) {
mTarget[X] += (int) view.getX();
mTarget[Y] += (int) view.getY();
view = (View) view.getParent();
}
}
}
And here's the layout. One important thing I found out is that the circle image view needed to have an elevation set so that it would lay out atop the toolbar in collapsed mode, otherwise it would be behind the toolbar and not shown.
<?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:id="#+id/coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.krislarson.customcoordinatorlayoutbehavior.ScrollingActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
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="280dp"
android:minHeight="108dp"
android:fitsSystemWindows="true"
app:title="Abby"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleGravity="center_horizontal"
app:expandedTitleMarginTop="140dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="#+id/background"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/sunset"
app:layout_collapseMode="parallax"
android:scaleType="centerCrop"/>
<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">
<Space
android:id="#+id/circle_collapsed_target"
android:layout_width="40dp"
android:layout_height="40dp"/>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_scrolling"/>
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/circle_image_view"
android:layout_width="120dp"
android:layout_height="120dp"
android:src="#drawable/abby"
android:layout_marginTop="220dp"
android:layout_gravity="top|center_horizontal"
android:elevation="8dp"
app:border_color="#android:color/black"
app:border_width="2dp"
app:collapsedTarget="#id/circle_collapsed_target"
app:layout_behavior="com.krislarson.customcoordinatorlayoutbehavior.CollapsingImageBehavior"/>
</android.support.design.widget.CoordinatorLayout>
You can see the entire demo project at https://github.com/klarson2/CustomCoordinatorLayoutBehavior
One possibility would be to create a custom view for your ToolBar and hide the red dot in the ToolBar if it is expanded and show an ImageView with the red dot instead (which is hidden when the toolbar is collapsed).
You can see how to add a custom view to a ToolBar at this answer: https://stackoverflow.com/a/27859966/5052976
After doing this just create a ImageView that is visible when the ToolBar is expanded.
final CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsingToolbarLayout);
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appBarLayout);
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) {
//show toolbar dot and hide imageview dot
isShow = true;
} else if(isShow) {
//hide toolbar dot and show imageview dot
isShow = false;
}
}
});
Unfortunately I can't test this right now but I think it should work ;-)
I'm developing an android app and I'm stuck in organizing the layout in a input form activity. I would like to organize the layout of my activity like this sample (found in google android's docs): https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bzhp5Z4wHba3Skg2b19UVS1LSmc/components_textfields_labels2.png . So a big app bar will contain one or two text field, referencing the name and the description of a user's activity, and within the activity layout's content the rest of input controls.
The behaviour I would reach is:
the activity title is initially empty and toolbar collapsed
when I get down the toolbar the text input appear and the user insert some text
when the user collapse the toolbar, the activity title (that is, the toolbar title) must be set to the input text value
The problem is that only one time this mechanism works: once set value and collapse the toolbar, when I get down again the toolbar, set the text input value and collapse the toolbar, the title is not setted, that is, setTitle has no effect over the first time.
I will now list my code: I tried to use a custom app bar layout, a collapsing tool bar layout, a toolbar and a text input in the following way:
<?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="wrap_content"
android:orientation="vertical"
tools:context="com.example.davide.inputformapp.MainActivity">
<com.example.davide.inputformapp.MyAppBarLayout.MyAppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="400dp"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginEnd="#dimen/activity_horizontal_margin"
app:expandedTitleMarginStart="#dimen/activity_horizontal_margin"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="parallax"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TextInputEditText
android:id="#+id/textInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.design.widget.CollapsingToolbarLayout>
</com.example.davide.inputformapp.MyAppBarLayout.MyAppBarLayout>
</android.support.design.widget.CoordinatorLayout>
where MyAppBarLayout is the class defined in this way(the code is not mine, I found here in a stackoverflow discussion):
public class MyAppBarLayout extends AppBarLayout
implements AppBarLayout.OnOffsetChangedListener {
private State state;
private OnStateChangeListener onStateChangeListener;
public MyAppBarLayout(Context context) {
super(context);
}
public MyAppBarLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (!(getLayoutParams() instanceof CoordinatorLayout.LayoutParams)
|| !(getParent() instanceof CoordinatorLayout)) {
throw new IllegalStateException(
"MyAppBarLayout must be a direct child of CoordinatorLayout.");
}
addOnOffsetChangedListener(this);
}
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (verticalOffset == 0) {
if (onStateChangeListener != null && state != State.EXPANDED) {
Log.d("MYAPP","---> EXPANDED");
onStateChangeListener.onStateChange(State.EXPANDED);
}
state = State.EXPANDED;
} else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
if (onStateChangeListener != null && state != State.COLLAPSED) {
Log.d("MYAPP","---> COLLAPSED");
onStateChangeListener.onStateChange(State.COLLAPSED);
}
state = State.COLLAPSED;
} else {
if (onStateChangeListener != null && state != State.IDLE) {
Log.d("MYAPP","---> IDLE");
onStateChangeListener.onStateChange(State.IDLE);
}
state = State.IDLE;
}
}
public void setOnStateChangeListener(OnStateChangeListener listener) {
this.onStateChangeListener = listener;
}
public interface OnStateChangeListener {
void onStateChange(State toolbarChange);
}
public enum State {
COLLAPSED,
EXPANDED,
IDLE
}
}
The code in the main activity's onCreate() method is:
toolbar = (Toolbar) findViewById(R.id.toolbar);
textInput = (TextInputEditText) findViewById(R.id.textInput);
final MyAppBarLayout collapsableAppBar = (MyAppBarLayout) findViewById(R.id.appbar);
setSupportActionBar(toolbar);
setTitle(null);
collapsableAppBar.setOnStateChangeListener(new MyAppBarLayout.OnStateChangeListener() {
#Override
public void onStateChange(MyAppBarLayout.State toolbarChange) {
String value = textInput.getText().toString();
toolbar.setTitle(value);
}
});
Any suggestion?
Thanks,
davide
set "android:id" to CollapsingToolbarLayout. find it in activity and set title to it.
I have tried many answers but only setting title to CollapsingToolbarLayout worked.
Please try to replace
toolbar.setTitle(value)
with
getSupportActionBar().setTitle(value)
as mentioned in this answer
You have to change title like this :
instead of
toolbar.setTitle(value);
do
getSupportActionBar.setTitle(value);
on
setOnStateChangeListener
it may not be a good solution but one way to get every thing working is by creating custom action Bar
custom_actionbar.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#drawable/yourcolorforactionbar" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textAllCaps="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#fff"
android:textStyle="bold" />
<ImageView
android:id="#+id/myimage"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="8dp"
android:src="#drawable/yourimagetoset" />
<ImageButton
android:id="#+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="8dp"
android:background="#null"
android:src="#android:drawable/menubutoon" />
</RelativeLayout>
mainactivity.class
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar mActionBar = getActionBar();
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null);
TextView mTitleTextView = (TextView) mCustomView.findViewById(R.id.title_text);
mTitleTextView.setText("My Own Title");
ImageButton imageButton = (ImageButton) mCustomView
.findViewById(R.id.imageButton);
imageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Refresh Clicked!",
Toast.LENGTH_LONG).show();
}
});
mActionBar.setCustomView(mCustomView);
mActionBar.setDisplayShowCustomEnabled(true);
}
}
In my application I have a collapsing Toolbar. If I start a specific Fragment I want to collapse the Toolbar so it behaves like a "normal" one and that the user can not expend it by himself. Here is my layout which I use for my Toolbar:
<android.support.design.widget.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:titleEnabled="false"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:src="#drawable/drawer_background"
app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
android:layout_width="match_parent"
android:layout_height="172dp"
android:scaleType="centerCrop"
app:layout_collapseMode="parallax"
android:minHeight="100dp" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolBar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:layout_scrollFlags="scroll|enterAlways" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
I also can collapse the layout from code like so:
appBarLayout.setExpanded(false, false);
final AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams();
params.setScrollFlags(0);
collapsingToolbarLayout.setLayoutParams(params);
But this does not help. If the user swipes down from the Toolbar it will expand.
Do you have any ideas why?
The core problem is that there is no CollapsingToolbarLayout.lock(); method up until now (v23.2.1 of support design). Hopefully, this feature will be included in a future version. Until then, I'm suggesting the following workaround:
You can collapse and lock your toolbar with:
appbar.setExpanded(false,false);
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams)appbar.getLayoutParams();
lp.height = (int) getResources().getDimension(R.dimen.toolbar_height);
and unlock it with:
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams)appbar.getLayoutParams();
lp.height = (int) getResources().getDimension(R.dimen.nav_header_height);
However, with the above code a problem occurs:
when forcefully collapsing CoordinatorLayout the title of our Toolbar is gone and CollapsingToolbarLayout.setTitle(CharSequence title); no longer works. To fix that we add a TextView in our Toolbar and manipulate its visibility accordingly. (we want it "gone" in a fragment that has its toolbar 'unlocked' and "visible" in a fragment that has its toolbar 'locked'.
We have to set TextView's android:textAppearance to be the same with CollapsingToolbarLayout's app:collapsedTitleTextAppearance to be consistent and avoid disrupting the user with different toolbar text sizes and colors.
In summary, with an interface like this:
public interface ToolbarManipulation {
void collapseToolbar();
void expandToolbar();
void setTitle(String s);
}
implemantations like these:
#Override
public void collapseToolbar(){
appbar.setExpanded(false,false);
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams)appbar.getLayoutParams();
lp.height = (int) getResources().getDimension(R.dimen.toolbar_height);
toolbarCollapsedTitle.setVisibility(View.VISIBLE);
}
#Override
public void expandToolbar() {
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams)appbar.getLayoutParams();
lp.height = (int) getResources().getDimension(R.dimen.nav_header_height);
toolbarCollapsedTitle.setVisibility(View.GONE);
}
#Override
public void setTitle(String s) {
collapsingToolbarLayout.setTitle(s);
toolbarCollapsedTitle.setText(s);
collapsingToolbarLayout.invalidate();
toolbarCollapsedTitle.invalidate();
}
and main xml like this:
....
<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"
app:collapsedTitleTextAppearance="#style/CollapsedAppBar"
>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_collapseMode="pin"
app:popupTheme="#style/AppTheme.PopupOverlay"
>
<TextView
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:visibility="gone"
android:layout_gravity="center_vertical|start"
android:gravity="center_vertical|start"
android:id="#+id/toolbar_collapsed_title"
android:textAppearance="#style/CollapsedAppBar"
/>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
......
you can lock and unlock your Toolbar as you like. Your fragments should call these functions in their onResume();
I've uploaded an example implementation here.
Note: This is just a workaround and obviously not the cleanest solution. We're waiting for a newer version of com.android.support to resolve this.
I'm not exactly sure if this is what you are looking for
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) params.getBehavior();
behavior.setDragCallback(new AppBarLayout.Behavior.DragCallback() {
#Override
public boolean canDrag(#NonNull AppBarLayout appBarLayout) {
return false;
}
});
Try to change the height of the AppBar. It works for me.
public void lockAppBar() {
int appbarHeight = (int)getResources().getDimension(R.dimen.your_fixed_appbar_height);
getView().findViewById(R.id.my_appbar).getLayoutParams().height = appbarHeight;
}
Do findViewById(R.id.image_view).setVisibility(View.GONE); where image_view is the id of the imageView in the collapsing toolbar. But if you want to do it for a specific fragment I suggest calling the same using fragment- activity communication.
None of the provided solutions worked for me except this one. With this solution, i can easily manage the state of collapsing toolbar. This will prevent expanding/enable collapsing of collapsing toolbar and set title for it.
public void lockAppBar(boolean locked,String title) {
if(locked){
appBarLayout.setExpanded(false, true);
int px = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 80, getResources().getDisplayMetrics());
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams)appBarLayout.getLayoutParams();
lp.height = px;
appBarLayout.setLayoutParams(lp);
collapsingToolbarLayout.setTitleEnabled(false);
toolbar.setTitle(title);
}else{
appBarLayout.setExpanded(true, false);
appBarLayout.setActivated(true);
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
lp.height = (int) getResources().getDimension(R.dimen.toolbarExpandHeight);
collapsingToolbarLayout.setTitleEnabled(true);
collapsingToolbarLayout.setTitle(title);
}
}
Well try setting some parameters to toolBar, tabLayout programatically, I have ViewPager changing flags on onPageSelected(int)
#Override
public void onPageSelected(int position) {
AppBarLayout.LayoutParams params = new AppBarLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
if (position == 3) {//listen for scrolls only for Fragment 3
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
toolBar.setLayoutParams(params);//hide as per scroll
params = new AppBarLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
tabLayout.setLayoutParams(params);//always visible
} else {
appBarLayout.setExpanded(false, true);
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED);
toolBar.setLayoutParams(params);//don't listen to scrolls
tabLayout.setLayoutParams(params);//dont listen to scrolls
}
}
Use/Set above flags as you required. AppBarLayout.LayoutParams
the simplest thing to do is to extend the class AppBarLayout.Behavior
public class AppBarBehavior extends AppBarLayout.Behavior {
private boolean locked;
public AppBarBehavior() {
super();
}
public AppBarBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onStartNestedScroll(#NonNull CoordinatorLayout parent, #NonNull AppBarLayout child, #NonNull View directTargetChild, View target, int nestedScrollAxes, int type) {
if (locked) return false; // Lock when content scrolled
else return super.onStartNestedScroll(parent, child, directTargetChild, target, nestedScrollAxes, type);
}
#Override
public boolean onTouchEvent(#NonNull CoordinatorLayout parent, #NonNull AppBarLayout child, #NonNull MotionEvent ev) {
if (locked) return false; // Lock when appBar swiped
else return super.onTouchEvent(parent, child, ev);
}
public void lock(boolean locked) {
this.locked = locked;
}
}
Then set new layout_behavior in XML
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/main.appbar"
android:layout_width="match_parent"
android:layout_height="200dp"
android:fitsSystemWindows="false"
app:layout_behavior="<full path to package>.AppBarBehavior">
And now you can manage locking with:
AppBarLayout appBar = findViewById(R.id.main_appbar);
appBar.setExpanded(false, true); // collapse appBar
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) appBar.getLayoutParams();
AppBarBehavior behavior = (AppBarBehavior) params.getBehavior();
behavior.lock(true); // lock appBar
I'm trying to do something really simple.
I would like the FAB to only appear on one tab in my TabLayout and be hidden when navigating to another tab. So for example, one tab would let you add new items in the FAB, but the next tab would not let you add items.
I have followed the 'typical' XML design layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/container"
xmlns:tools="http://schemas.android.com/tools"
>
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|enterAlways">
<LinearLayout
android:id="#+id/search_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal">
<EditText
android:id="#+id/search_view"
android:layout_width="0dp"
android:layout_height="?attr/actionBarSize"
android:layout_weight="1"
android:background="#android:color/transparent"
android:gravity="center_vertical"
android:hint="Search"
android:imeOptions="actionSearch"
android:inputType="text"
android:maxLines="1"
android:paddingLeft="2dp"
android:singleLine="true"
android:textColor="#ffffff"
android:textColorHint="#b3ffffff" />
<ImageView
android:id="#+id/search_clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:src="#drawable/ic_action_cancel" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:tabMode="scrollable"
/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="com.example.simon.behaviours.PatchedScrollingViewBehavior"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
app:borderWidth="0dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_new"
android:layout_margin="16dp"
android:layout_gravity="bottom|right"
app:layout_anchor="#+id/viewPager"
app:layout_anchorGravity="bottom|right|end"
app:layout_behavior="com.example.simon.behaviours.ScrollingFABBehavior"
android:visibility="gone"
app:fabSize="normal">
</android.support.design.widget.FloatingActionButton>
</android.support.design.widget.CoordinatorLayout>
I have used the following behavior for the FAB. This results in any upscrolls to cause the FAB to disappear and will return back on screen on a downscroll:
public class ScrollingFABBehavior extends FloatingActionButton.Behavior {
private int toolbarHeight;
public ScrollingFABBehavior(Context context, AttributeSet attrs) {
super();
this.toolbarHeight = getToolbarHeight(context);
}
#Override
public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionButton fab, View dependency) {
return super.layoutDependsOn(parent, fab, dependency) || (dependency instanceof AppBarLayout);
}
#Override
public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton fab, View dependency) {
boolean returnValue = super.onDependentViewChanged(parent, fab, dependency);
if (dependency instanceof AppBarLayout) {
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
int fabBottomMargin = lp.bottomMargin;
int distanceToScroll = fab.getHeight() + fabBottomMargin;
float ratio = (float)dependency.getY()/(float)toolbarHeight;
fab.setTranslationY(-distanceToScroll * ratio);
}
return returnValue;
}
public static int getToolbarHeight(Context context) {
final TypedArray styledAttributes = context.getTheme().obtainStyledAttributes(
new int[]{R.attr.actionBarSize});
int toolbarHeight = (int) styledAttributes.getDimension(0, 0);
styledAttributes.recycle();
return toolbarHeight;
}
}
I have added a viewpager addOnPageChangeListener:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position == 0) {
FloatingActionButton floatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
floatingActionButton.setVisibility(View.VISIBLE);
}
else
{
FloatingActionButton floatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
floatingActionButton.setVisibility(View.GONE);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
I only want the FAB to appear on the first page and disappear on all the other pages.
The code works but when I swipe down on the next page, the FAB appears after even though the visibility is set to gone. I think it has something to do with the behavior set for the FAB. Does anyone know why the FAB still become visible on a swipe down if the visibility is set to gone?
This didn't end up being something I want to implement in my app but I did manage to find an answer in the end, with some help by looking through how they implemented the same thing on the wordpress app.
In the wordpress app, we see a floating action button on the first page of the app which disappears if you swipe to any of the other pages on the viewpager:
They did this through the following code - this is the code for the Activity that holds the viewpager. You can see the relevant part of the code under the onPageScrolled method which contains the eventbus that posts an event each time the page is scrolled. The event only contains one variable called positionOffset which is an integer value from 0 to 1. If you scroll and the page is half way between the two viewpagers, the positionOffset is 0.5, you get the idea:
WPMainActivity.java
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
AppPrefs.setMainTabIndex(position);
switch (position) {
case WPMainTabAdapter.TAB_NOTIFS:
new UpdateLastSeenTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
break;
}
trackLastVisibleTab(position);
}
#Override
public void onPageScrollStateChanged(int state) {
// noop
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// fire event if the "My Site" page is being scrolled so the fragment can
// animate its fab to match
if (position == WPMainTabAdapter.TAB_MY_SITE) {
EventBus.getDefault().post(new MainViewPagerScrolled(positionOffset));
}
}
});
The event is picked up in the fragment which contains the following code. The event will fire off the translationY method which animates the FAB vertically when the page is scrolled according to how far the page is scrolled out of view as determined by the positionOffset:
MySiteFragment
/*
* animate the fab as the users scrolls the "My Site" page in the main activity's ViewPager
*/
#SuppressWarnings("unused")
public void onEventMainThread(CoreEvents.MainViewPagerScrolled event) {
mFabView.setTranslationY(mFabTargetYTranslation * event.mXOffset);
}
Finally, the layout in the my_site_fragment.xml shows you that the FAB is actually placed into the fragments xml instead of the activity xml.
<!-- this coordinator is only here due to https://code.google.com/p/android/issues/detail?id=175330 -->
<android.support.design.widget.CoordinatorLayout
android:id="#+id/coordinator"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_marginBottom="#dimen/fab_margin"
android:layout_marginRight="#dimen/fab_margin"
android:src="#drawable/gridicon_create_light"
app:borderWidth="0dp"
app:rippleColor="#color/fab_pressed" />
</android.support.design.widget.CoordinatorLayout>
Hey I had exactly the same issue as you.
I found two methods which worked for me.
Method 1:
Add a static flag in your MainActivity:
public static boolean fabVisible;.
I noticed you have a listener for your viewPager to detect the current fragment page, so you can add this:
public void onPageSelected(int position) {
switch (position) {
case 0:
fabVisible = true;
mFloatingActionButton.show();
break;
default:
fabVisible = false;
mFloatingActionButton.hide();
break;
}
}
And inside your custom fab behaviour, add the following code:
if (dyConsunmed > 0 && child.getVisibility() == View.VISIBLE ) {
child.hide();
} else if (dyConsunmed < 0 && child.getVisibility() != View.VISIBLE && MainActivity.fabVisible) {
child.show();
}
The point of this method is to make sure the fab should be visible before you implement the hide & show method.
Method 2:
You don't need to add any flag like "fabVisible" in your MainActivity anymore. Although this method does require you to set the viewPager as static in your MainActivity, because we need to be able to access it in our custom fab behaviour class.
In your ScrollAwareFABBehavior class, add the following code:
if (MainActivity.viewPager.getCurrentItem() == 0) {
if (dyConsunmed > 0 && child.getVisibility() == View.VISIBLE ) {
child.hide();
} else if (dyConsunmed < 0 && child.getVisibility() != View.VISIBLE) {
child.show();
}
}
The key point of this method, is only to make the show and hide method when you are inside the fragment you want (In my case it's fragment one so the currenItem == 0). Of course in order to remove the fab in the second fragment, you still need to hide it within your viewPager listener.
If you still feel confused about the implement, feel free to check my repository on GitHub and play with the code. The address is: https://github.com/Anthonyeef/FanfouDaily
Though the feed content is all in Chinese, the code is all in English.
Implement ViewPager.onPageListener and over ride onPageSelected and show or hide FAB on Tabs as per your requirements following is the sample code:
#Override
public void onPageSelected(int position) {
//FAB_PAGE is the index of the page on which you want to show FAB
if(position == FAB_PAGE)
{
fab.setVisibility(View.VISIBLE);
}
else
{
fab.setVisibility(View.GONE);
}
}
You can also use fab.show(); and fab.hide();
Also check this for further details.
You can do it programmatically when you swipe to the next tab.
FloatingActionButton fab = (FloatingActionButton) view.findViewByID(R.id.fab)
fab.setVisibility(View.GONE);
And then set the visiblity to View.VISIBLE when you swipe back.
Create a static boolean in your activity (see YourActivity.isFABinCurrentTabVisible below) and alter it from your ViewPager, accordingly if there should be a fab in the current tab or not.
Might be a dirty fix though...
And consider using fab.show() and fab.hide() instead of setVisiblity(). These perform the fade-in and fade-out animations.
public class ScrollAwareFABBehavior extends FloatingActionButton.Behavior {
public ScrollAwareFABBehavior(Context context, AttributeSet attrs) {
super();
}
#Override
public boolean onStartNestedScroll(final CoordinatorLayout coordinatorLayout, final FloatingActionButton child,
final View directTargetChild, final View target, final int nestedScrollAxes) {
// Ensure we react to vertical scrolling
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL
|| super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes);
}
#Override
public void onNestedScroll(final CoordinatorLayout coordinatorLayout, final FloatingActionButton child,
final View target, final int dxConsumed, final int dyConsumed,
final int dxUnconsumed, final int dyUnconsumed) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
if (dyConsumed > 0 && child.getVisibility() == View.VISIBLE) {
// User scrolled down and the FAB is currently visible -> hide the FAB
child.hide();
} else if (dyConsumed < 0 && child.getVisibility() != View.VISIBLE && YourActivity.isFABinCurrentTabVisible) {
// User scrolled up and the FAB is currently not visible -> show the FAB
child.show();
}
}
}
It sounds like you're approaching this from the wrong angle...
So for example, one tab would let you add new items in the FAB, but the next tab would not let you add items.
Put the FAB in the Fragment of the first page instead of the hosting Fragment / Activity. That way it will automatically disappear along with the first page fragment - it will even animate alongside it. It will also be where it belongs, since it's not at all related to the other pages / tabs.
If you really need to handle the click event in your hosting Fragment / Activity, make your first page fragment call back to the hosting Fragment / Activity when that click occurs.