借助View的OnTouchListener接口來監(jiān)聽listView的滑動,通過比較與上次坐標的大小,判斷滑動方向,并通過滑動方向來判斷是否需顯示或者隱藏對應(yīng)的布局,并且?guī)в袆赢嬓Ч?br />
1.自動顯示隱藏Toolbar
首先給listView增加一個HeaderView,避免第一個Item被Toolbar遮擋。
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為系統(tǒng)ActionBar的高度
定義一個mTouchSlop變量,獲取系統(tǒng)認為的最低滑動距離
mTouchSlop=ViewConfiguration.get(this).getScaledTouchSlop();//系統(tǒng)認為的最低滑動距離
判斷滑動事件
bbsListView.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {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); //隱藏上方的viewmShow=!mShow;}}else if(direction==0){if(!mShow){toolbarAnim(0); //展示上方的viewmShow=!mShow;}}case MotionEvent.ACTION_UP:break;}return false;}});}屬性動畫
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的,不然會引起沖突。同時引入編譯
dependencies{compile fileTree(include:['*.jar'],dir:'libs')compile 'com.android.support:appcompat-v7:21.0.3'}2.當(dāng)要隱藏和顯示的組件不是toolbar,而是我們自定義的布局myView時,需要注意一些點,
(1) 布局要用相對布局,讓我們自定義的布局懸浮在listView上方。
(2)避免第一個Item被myView遮擋,給listView增加一個HeaderView,此時需要測量myView的高度,要用下面這種方法,把任務(wù)post到UI線程中,不然執(zhí)行會出錯。
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一樣
以上所述是小編給大家介紹的Android ListView自動顯示隱藏布局的實現(xiàn)方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對武林網(wǎng)網(wǎng)站的支持!
新聞熱點
疑難解答