滑动隐藏标题栏布局ListView

来源:互联网 发布:开淘宝微店能赚钱吗 编辑:程序博客网 时间:2024/05/21 10:17

由于手机屏幕有限,有时候列表展示时,为了尽可能多的为用户展示列表数据,当用户向上滑动手指,查看更多数据时,可以把标题栏隐藏,从而为用户展示更多的数据。
这里写图片描述
向上滑动时,隐藏标题栏
这里写图片描述
实现起来也比较简单,步骤如下:

  1. 为ListView添加监听手势
  2. 当用户向上滑动时隐藏标题栏
  3. 当用户向下滑动时显示标题栏
    总体思路比较简单,为ListView添加一个onTouchListener,判断用户当前触发的手势,进行相应的视图布局的显示和隐藏。关于视图的显示的隐藏有很多种方式,我们这里使用的是属性动画。
  mListView.setOnTouchListener(new View.OnTouchListener() {            @Override            public 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) {                            // 下滑 显示titleBar                            showHideTitleBar(true);                        } else if (mFirstY - mCurrentY > mTouchSlop) {                            // 上滑 隐藏titleBar                            showHideTitleBar(false);                        }                        break;                    case MotionEvent.ACTION_UP:                        break;                }                return false;            }        });
 private void showHideTitleBar(boolean tag) {        if (mAnimatorTitle != null && mAnimatorTitle.isRunning()) {            mAnimatorTitle.cancel();        }        if (mAnimatorContent != null && mAnimatorContent.isRunning()) {            mAnimatorContent.cancel();        }        if (tag) {            mAnimatorTitle = ObjectAnimator.ofFloat(mTitle, "translationY", mTitle.getTranslationY(), 0);            mAnimatorContent = ObjectAnimator.ofFloat(mListView, "translationY", mListView.getTranslationY(), getResources().getDimension(R.dimen.title_height));        } else {            mAnimatorTitle = ObjectAnimator.ofFloat(mTitle, "translationY", mTitle.getTranslationY(), -mTitle.getHeight());            mAnimatorContent = ObjectAnimator.ofFloat(mListView, "translationY", mListView.getTranslationY(),0);        }        mAnimatorTitle.start();        mAnimatorContent.start();    }

这里为了有较好的用户体验使用了一个属性动画,当然你也可以简单的使用Visible属性来控制标题栏的显示和隐藏,需要注意的是,注意计算标题栏显示隐藏时,ListView位置进行相应的改变,demo中同样也使用的属性动画进行相应位置的改变。
源码地址

2 0