Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
ScrollingToolBar
package com.scrolltoolbar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class MainActivity extends ActionBarActivity {
@InjectView(R.id.toolbar) Toolbar mToolBar;
@InjectView(R.id.recyclerView) RecyclerView mRecyclerview;
private int scrolledDistance = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
setSupportActionBar(mToolBar);
mRecyclerview.setLayoutManager(new LinearLayoutManager(this));
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(createItemList());
mRecyclerview.setAdapter(recyclerAdapter);
mRecyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if(newState == RecyclerView.SCROLL_STATE_IDLE){
if(scrolledDistance < -mToolBar.getHeight()/2){
mToolBar.animate().translationY(-mToolBar.getHeight()).setInterpolator(new DecelerateInterpolator()).start();
scrolledDistance = -mToolBar.getHeight();
}else{
mToolBar.animate().translationY(0).setInterpolator(new AccelerateInterpolator()).start();
scrolledDistance = 0;
}
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
scrolledDistance -= dy;
if(dy > 0 ) {
checkHeight();
mToolBar.setTranslationY(scrolledDistance);
}else if(dy < 0 ){
checkHeight();
mToolBar.setTranslationY(scrolledDistance);
}
}
});
}
private void checkHeight() {
if(scrolledDistance > 0) {
scrolledDistance = 0;
} else if(scrolledDistance <= -mToolBar.getHeight()) {
scrolledDistance = -mToolBar.getHeight();
}
}
private List<String> createItemList() {
List<String> itemList = new ArrayList<>();
for(int i=0;i<2000;i++) {
itemList.add("Item "+i);
}
return itemList;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment