欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 根据手势顶部View自动展示与隐藏效果

程序员文章站 2023-12-01 08:21:46
首先来看一下效果:    大体思路如下: 总体布局用了一个自定义的viewgroup,里面包了两个view(top view,bottomvi...

首先来看一下效果:

Android 根据手势顶部View自动展示与隐藏效果 

 大体思路如下:

总体布局用了一个自定义的viewgroup,里面包了两个view(top view,bottomview)

我在bottomview里放了viewpager,里面又有fragment,fragment里放的是listview

原理:

viewgroup在分发touchevent的时候先通过手势gesturedetector判断手势方向,当向上滑动的时候让topview和bottomview同时向上移动,反之亦然。

整体思路不是很难如下是干货:

布局文件

<com.lin.gesturedetector.myviewgroup
  android:id="@+id/view_group"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <include
   android:id="@+id/group_top"
   layout="@layout/view_top" />
  <include
   android:id="@+id/group_bottom"
   layout="@layout/view_bottom" />
 </com.lin.gesturedetector.myviewgroup>

手势监听重要的是打log看一下上下滑动是数值的变化,找到其规律:           

 @override
   public boolean onscroll(motionevent e1, motionevent e2, float distancex, float distancey) {
    log.i(tag, "onscroll -> distancey" + distancey);
    if (distancey < 0) {// 手势向下滑动是负值
     animatorlayoutoffset(1);
    }
    if (distancey > 0) {
     animatorlayoutoffset(0f);
    }
    return true;
   }

一定记得在viewgroup内查找控件需要在onfinishinflate后才能找到:   

 @override
 protected void onfinishinflate() {
  super.onfinishinflate();
  viewtop = findviewbyid(r.id.group_top);
  viewbottom = findviewbyid(r.id.group_bottom);
 }

在viewgroup布局的逻辑中需要处理的有一下几点:

1、onmeasure的时候要把子控件测量出来

2、onlayout时需要手动将子控件布局

接下来就是监听手势设置动画,不停的onlayout以达到topview和bottomview的布局效果  

@override
 protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
  int width = measurespec.getsize(widthmeasurespec);
  int height = measurespec.getsize(heightmeasurespec);
  viewtop.measure(measurespec.makemeasurespec(width, measurespec.exactly), measurespec.makemeasurespec(height, measurespec.at_most));
  viewbottom.measure(measurespec.makemeasurespec(width, measurespec.exactly), measurespec.makemeasurespec(height, measurespec.exactly));
  setmeasureddimension(width, height);
 }
 @override
 protected void onlayout(boolean changed, int l, int t, int r, int b) {
  int topheight = viewtop.getmeasuredheight();
  float offset = layoutoffset * topheight;
  int width = r - l;
  float topviewytop = offset - topheight;
  float topviewybottom = topviewytop + topheight;
  viewtop.layout(0, (int) topviewytop, width, (int) topviewybottom);
  viewbottom.layout(0, (int) topviewybottom, width, (int) topviewybottom + viewbottom.getmeasuredheight());
 }
 private void animatorlayoutoffset(float offset) {
  if (animator != null && animator.isrunning()) {
   return;
  }
  animator = objectanimator.offloat(this, "layoutoffset", layoutoffset, offset);
  animator.setduration(500);
  animator.start();
 }

项目地址在这:

github

总结

以上所述是小编给大家介绍的android 根据手势顶部view自动展示与隐藏效果,希望对大家有所帮助