当前位置: 移动技术网 > 移动技术>移动开发>Android > 神奇的listView实现自动显示隐藏布局Android代码

神奇的listView实现自动显示隐藏布局Android代码

2019年07月24日  | 移动技术网移动技术  | 我要评论

借助view的ontouchlistener接口来监听listview的滑动,通过比较与上次坐标的大小,判断滑动方向,并通过滑动方向来判断是否需显示或者隐藏对应的布局,并且带有动画效果。

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为系统actionbar的高度

定义一个mtouchslop变量,获取系统认为的最低滑动距离

复制代码 代码如下:
mtouchslop=viewconfiguration.get(this).getscaledtouchslop();//系统认为的最低滑动距离
      

判断滑动事件

bbslistview.setontouchlistener(new 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)
      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;
   }
  });
 }

属性动画 

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.当要隐藏和显示的组件不是toolbar,而是我们自定义的布局myview时,需要注意一些点,
(1) 布局要用相对布局,让我们自定义的布局悬浮在listview上方。
(2)避免第一个item被myview遮挡,给listview增加一个headerview,此时需要测量myview的高度,要用下面这种方法,把任务post到ui线程中,不然执行会出错。 

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一样

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网