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

Android ListView自动显示隐藏布局的实现方法

程序员文章站 2024-03-31 18:58:58
借助view的ontouchlistener接口来监听listview的滑动,通过比较与上次坐标的大小,判断滑动方向,并通过滑动方向来判断是否需显示或者隐藏对应的布局,并且...

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

以上所述是小编给大家介绍的android listview自动显示隐藏布局的实现方法,希望对大家有所帮助