借助View的OnTouchListener接口来监听listView的滑动,通过比较与上次坐标的大小,判断滑动方向,并通过滑动方向来判断是否需显示或者隐藏对应的布局,并且带有动画效果。
1.自动显示隐藏Toolbar
首先给listView增加一个HeaderView,避免第一个Item被Toolbar遮挡。
1 2 3 4 5 |
View header=new View(this); header.setLayoutParams(new AbsListView.LayoutParams( AbsListView.LayoutParams.MATCH_PARENT, (int)getResources().getDimension(R.dimen.abc_action_bar_default_height_material))); mListView.addHeaderView(header); |
//R.dimen.abc_action_bar_default_height_material为系统ActionBar的高度
定义一个mTouchSlop变量,获取系统认为的最低滑动距离
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
bbsListView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { 6 switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mFirstY=event.getY(); break; case MotionEvent.ACTION_MOVE: mCurrentY=event.getY(); if(mCurrentY-mFirstY>mTouchSlop) direction=0; //listView向下滑动 else if(mFirstY-mCurrentY>mTouchSlop) direction=1; //listView向上滑动 if(direction==1) { if(mShow) { toolbarAnim(1); //隐藏上方的view mShow=!mShow; } } else if(direction==0) { if(!mShow) { toolbarAnim(0); //展示上方的view mShow=!mShow; } } case MotionEvent.ACTION_UP: break; } return false; } }); } |
属性动画
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
protected void toolbarAnim(int flag) { if(set!=null && set.isRunning()) { set.cancel(); } if(flag==0) { mAnimator1=ObjectAnimator.ofFloat(mToolbar, "translationY", linearView.getTranslationY(),0); mAnimator2=ObjectAnimator.ofFloat(mToolbar, "alpha", 0f,1f); } else if(flag==1) { mAnimator1=ObjectAnimator.ofFloat(mToolbar, "translationY", linearView.getTranslationY(),-linearView.getHeight()); mAnimator2=ObjectAnimator.ofFloat(mToolbar, "alpha", 1f,0f); } set=new AnimatorSet(); set.playTogether(mAnimator1,mAnimator2); set.start(); } |
//上面为位移还有透明度属性动画
使用的时候theme要用NoActionBar的,不然会引起冲突。同时引入编译
1 2 3 4 |
1 dependencies{ 2 compile fileTree(include:['*.jar'],dir:'libs') 3 compile 'com.android.support:appcompat-v7:21.0.3' 4 } |
2.当要隐藏和显示的组件不是toolbar,而是我们自定义的布局myView时,需要注意一些点,
(1) 布局要用相对布局,让我们自定义的布局悬浮在listView上方。
(2)避免第一个Item被myView遮挡,给listView增加一个HeaderView,此时需要测量myView的高度,要用下面这种方法,把任务post到UI线程中,不然执行会出错。
1 2 3 4 5 6 7 8 |
final View header=new View(this); //给listView增加一个headView,避免第一个item被遮挡 header.post(new Runnable() { public void run() { header.setLayoutParams(new AbsListView.LayoutParams( AbsListView.LayoutParams.MATCH_PARENT, myView.getHeight())); } }); |
其他的与toolbar一样
转载请标明出处:http://77blogs.com/?p=27