效果图
![这里写图片描述](https://img-blog.csdn.net/20160530112908186)
代码
public class MainActivity extends AppCompatActivity {
private ListView listView;
String[] datas = {"A","A","A","A","A","A","A","A","A","A",
"A","A","A","A","A","A","A","A","A","A","A","A","A",};
private int scaledTouchSlop;
private float firstY = 0;
private Toolbar toolbar;
private ObjectAnimator animtor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
listView = (ListView) findViewById(R.id.listview);
initHeadView();
listView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,datas));
scaledTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop();
listView.setOnTouchListener(new View.OnTouchListener() {
private float currentY;
private int direction;
private boolean mShow = true;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
firstY = event.getY();
break;
case MotionEvent.ACTION_MOVE:
currentY = event.getY();
if(currentY - firstY >scaledTouchSlop){
direction = 0;
}else if(firstY - currentY > scaledTouchSlop){
direction = 1;
}
if(direction == 1){
if(mShow){
toobarAnim(1);
mShow = !mShow;
}
}else if(direction == 0){
if(!mShow){
toobarAnim(0);
mShow = !mShow;
}
}
break;
case MotionEvent.ACTION_UP:
break;
}
return false;
}
});
}
/**
* 设置头布局,注意:这个头布局的高度要和ToolBar的高度一致
*/
public void initHeadView(){
View view = new View(this);
AbsListView.LayoutParams params = new AbsListView.LayoutParams
(AbsListView.LayoutParams.MATCH_PARENT,
(int)getResources().getDimension(R.dimen.abc_action_bar_default_height_material));
view.setLayoutParams(params);
listView.addHeaderView(view);
}
public void toobarAnim(int direction){
if(animtor!=null&&animtor.isRunning()){
animtor.cancel();
}
if(direction == 0){
animtor = ObjectAnimator.ofFloat(toolbar, "translationY", toolbar.getTranslationY(), 0);
}else if( direction == 1){
animtor = ObjectAnimator.ofFloat(toolbar, "translationY", toolbar.getTranslationY(), -toolbar.getHeight());
}
animtor.start();
}
}