当前位置: 移动技术网 > IT编程>移动开发>Android > Android UI设计系列之自定义ListView仿QQ空间阻尼下拉刷新和渐变菜单栏效果(8)

Android UI设计系列之自定义ListView仿QQ空间阻尼下拉刷新和渐变菜单栏效果(8)

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

重庆工业职业技术学校,宦海沉香,存钱英语

好久没有写有关ui的博客了,刚刚翻了一下之前的博客,最近一篇有关ui的博客:android ui设计系列之自定义dialog实现各种风格的对话框效果(7) ,实现各种风格效果的对话框,在那篇博客写完后由于公司封闭开发封网以及其它原因致使博客中断至今,中断这么久很是惭愧,后续我会尽量把该写的都补充出来。近来项目有个需求,要做个和qq空间类似的菜单栏透明度渐变和下拉刷新带有阻尼回弹的效果。于是花点时间动手试了试,基本上达到了qq空间的效果,截图如下:

        通过观察qq空间的运行效果,发现当往上滚动时菜单栏会随着滚动距离的增大其透明度组件增大直到完全不透明,反之逐渐透明。当滚动到顶部后继续下拉会出现拉升效果当松手之后出现阻尼回弹效果。于是就通过重写listview模仿了qq空间的运行效果。
实现qq空间运行效果前需要考虑两个问题:
1)、如何实现菜单栏透明度渐变
        通过观察qq空间的运行效果可知其菜单栏的透明度是根据滚动距离而动态变化的,要想实现透明度的变化就需要知道的listview的滚动距离,所以有关透明度的问题也就转化成了滚动距离的问题。
2)、如何实现阻尼拉升和回弹效果
        要想利用listview实现阻尼效果就要求listview首先滚动到了顶部,当listview滚动到了顶部之后若继续手动下滑就要求其第一个child变化来模拟下拉效果,当手指松开后该child要回弹到初始状态。
        我们先看第一个问题:要想实现透明度渐变就要先获取到listview的滚动距离,通过滚动距离来计算相应的透明度。由于listview的复用机制就决定了不能通过第一个可见item的gettop()方法来得到滚动值,所以我们可以通过headerview来获取滚动距离,因为header在listview中是不参与复用的。
        下面先了解一下listview添加headerview后的滚动流程:

上图大致画了listview含有headerview时的三个滚动状态,状态一可称为初始状态或者是恰好滚动到最顶部状态,此时headerview的gettop()值为0;状态二为listview的滚动中状态,此时headerview没有完全滚动出listview边界,gettop()的返回值为负数且其绝对值范围在0和headerview的高度之间;状态三表示的是headerview完全滚动出了listview边界,若调用gettop()得到的返回值为负数且绝对值等于headerview的高度(此后可理解成headerview一直固定在listview的顶部)。
        明白了listview的滚动原理,我们先尝试实现渐变菜单栏的功能。首先定义自己的listview,取名为flexiblelistview,单词flexible是灵活的、多样的的意思,因为我们的listview不仅要实现菜单栏的透明度渐变还要实现阻尼效果,所以取名为flexiblelistview比较恰当。flexiblelistview继承listview后需要实现其构造方法,代码如下:

public class flexiblelistview extends listview { 
 
 public flexiblelistview(context context) { 
 super(context); 
 } 
 
 public flexiblelistview(context context, attributeset attrs) { 
 super(context, attrs); 
 } 
 
 public flexiblelistview(context context, attributeset attrs, int defstyleattr) { 
 super(context, attrs, defstyleattr); 
 } 
 
 @targetapi(21) 
 public flexiblelistview(context context, attributeset attrs, int defstyleattr, int defstyleres) { 
 super(context, attrs, defstyleattr, defstyleres); 
 } 
} 

        flexiblelistview仅仅是继承了listview,这本质上和listview没有区别。既然我们是通过给listview添加headerview的方式来判断滚动距离,那就要获取到headerview对象。怎么获取到headerview对象呢?这里有个技巧,由于给listview添加headerview最终是调用listview的addheaderview(view v, object data, boolean isselected)方法,所以我们可以重写该方法,取到添加进来的第一个headerview,那怎么判断是第一个添加进来的headerview呢?因为headerview的添加是有序的即先添加的先绘制。所以可以定义一个代表第一个headerview的属性mheaderview,当调用到addheaderview()方法时通过判断mheaderview的值是否为空,如果为空就赋值否则不赋值,代码如下:

public class flexiblelistview extends listview { 
 
 private view mheaderview; 
 private int mmaxscrollheight; 
 
 public flexiblelistview(context context) { 
 super(context); 
 } 
 
 public flexiblelistview(context context, attributeset attrs) { 
 super(context, attrs); 
 } 
 
 public flexiblelistview(context context, attributeset attrs, int defstyleattr) { 
 super(context, attrs, defstyleattr); 
 } 
 
 @targetapi(21) 
 public flexiblelistview(context context, attributeset attrs, int defstyleattr, int defstyleres) { 
 super(context, attrs, defstyleattr, defstyleres); 
 } 
 
 @override 
 public void addheaderview(view v, object data, boolean isselectable) { 
 super.addheaderview(v, data, isselectable); 
 if(null == mheaderview) { 
 mheaderview = v; 
 mmaxscrollheight = mheaderview.getlayoutparams().height; 
 } 
 } 
} 

         flexiblelistview中定义了mheaderview和mmaxscrollheight属性,在addheaderview()方法中对mheaderview做非空判断来获取到第一个headerview并赋值给mheadereview,mmaxscrollheight表示headerview的最大滚动距离,当headerview的滚动距离超过此值我们就要设置菜单栏不透明否则就更改透明度。在这里我直接使用了headerview的高度来表示其允许滚动的最大距离。
        现在可以获取到listview的第一个headerview,接下来就是判断listview的滚动了,这时候有的童靴可能会想到采用给listview添加scrolllistener的方式,这种方式是可行的,但我们这次不采用添加listener的方式,如果你对listview的源码比较熟悉的话就清楚触发onitemscrolllistener的回调时机是在abslistview的invokeonitemscrolllistener()方法中,该方法源码如下:

/** 
 * notify our scroll listener (if there is one) of a change in scroll state 
 */ 
void invokeonitemscrolllistener() { 
 if (mfastscroll != null) { 
 mfastscroll.onscroll(mfirstposition, getchildcount(), mitemcount); 
 } 
 if (monscrolllistener != null) { 
 monscrolllistener.onscroll(this, mfirstposition, getchildcount(), mitemcount); 
 } 
 onscrollchanged(0, 0, 0, 0); // dummy values, view's implementation does not use these. 
} 

        invokeonitemscrolllistener()方法就是触发滚动回调的,无论我们给不给listview设置onitemscrolllistener那该方法都会调用,细心的同学可能发现在该方法最后调用了view的onscrollchanged()方法,这时候你恍然大悟,我们可以重写该方法呀,当listview发生滚动了也就调用了onscrollchange()方法,多省事呀。呵呵,恭喜你,答对了,我们今天就是采用重写onscrollchanged()方法并在该方法中通过判断listview的headerview的滚动距离来设置菜单栏的透明度的。
        现在我们清楚了listview的滚动时机,也有了headerview和最大滚动距离,接下来就是分析实现渐变的条件了:要实现渐变我们就要清楚是谁要渐变,在我们的app中可能是actionbar,也可能是toolbar,还有可能是我们自定义的一个viewgroup来模拟的actionbar,所以flexiblelistview得有个代表actionbar的mactionbar属性并对外提供一个方法bindactionbar(),该方法就表示把需要实现渐变的actionbar传递进来,代码如下:

public class flexiblelistview extends listview { 
 
 private view mactionbar; 
 private view mheaderview; 
 private int mmaxscrollheight; 
 private drawable mactionbarbackground; 
 
 public flexiblelistview(context context) { 
 super(context); 
 } 
 
 public flexiblelistview(context context, attributeset attrs) { 
 super(context, attrs); 
 } 
 
 public flexiblelistview(context context, attributeset attrs, int defstyleattr) { 
 super(context, attrs, defstyleattr); 
 } 
 
 @targetapi(21) 
 public flexiblelistview(context context, attributeset attrs, int defstyleattr, int defstyleres) { 
 super(context, attrs, defstyleattr, defstyleres); 
 } 
 
 @override 
 protected void onscrollchanged(int l, int t, int oldl, int oldt) { 
 super.onscrollchanged(l, t, oldl, oldt); 
 if(null != mactionbarbackground) { 
 mactionbarbackground.setalpha(evaluatealpha(math.abs(mheaderview.gettop()))); 
 } 
 } 
 
 @override 
 public void addheaderview(view v, object data, boolean isselectable) { 
 super.addheaderview(v, data, isselectable); 
 if(null == mheaderview) { 
 mheaderview = v; 
 mmaxscrollheight = mheaderview.getlayoutparams().height; 
 } 
 } 
 
 private int evaluatealpha(int t) { 
 if (t >= mmaxscrollheight) { 
 return 255; 
 } 
 return (int) (255 * t /(float) mmaxscrollheight); 
 } 
 
 public void bindactionbar(view actionbar) { 
 if(null != actionbar) { 
 mactionbar = actionbar; 
 mactionbarbackground = actionbar.getbackground(); 
 if(null == mactionbarbackground) { 
 mactionbarbackground = new colordrawable(color.transparent); 
 } 
 mactionbarbackground.setalpha(0); 
 if(build.version.sdk_int >= 16) { 
 mactionbar.setbackground(mactionbarbackground); 
 } else { 
 mactionbar.setbackgrounddrawable(mactionbarbackground); 
 } 
 } 
 } 
 
 public void bindactionbar(actionbar actionbar) { 
 if(null != actionbar) { 
 // todo impl with actionbar 
 // actionbar.setbackgrounddrawable(); 
 } 
 } 
} 

        flexiblelistview新增了mactionbar和mactionbarbackground属性,mactionbar代表需要渐变的菜单栏,mactionbarbackground为菜单栏的背景。其次对外提供了重载方法bindactionbar(),参数为actionbar的方法是空实现,里边添加了todo提示符并给了setbackgrounddrawable()提示(注意actionbar实现渐变需要设置windowfeature),希望童靴们自己可以实现出来。
        flexiblelistview中重写了onscrollchanged()方法,在该方法中通过获取mheaderview的gettop()值然后调用evaluatealpha()方法计算出alpha值,evaluatealpha()的计算很简单,当滚动值超过了最大滚动距离mmaxscrollheight就返回255(255表示不透明,0表示透明),否则计算出当前滚动值所对应的alpha值,最后通过调用mactionbarbackground的setalpha()来达到mactionbar的透明度变化。
        现在实现菜单栏的透明度的逻辑准备就绪了,我们先测试一下看看,定义菜单栏布局,代码如下:

<?xml version="1.0" encoding="utf-8"?> 
<framelayout xmlns:android="http://schemas.android.com/apk/res/android" 
 android:layout_width="match_parent" 
 android:layout_height="@dimen/action_bar_height" 
 android:background="#aabbcc" 
 android:clickable="true" 
 android:orientation="vertical" 
 android:paddingleft="10dp"> 
 
 <textview 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:layout_gravity="center_vertical" 
 android:drawableleft="@mipmap/back" 
 android:text="动态" 
 android:textcolor="#b8e7fe" 
 android:textsize="17sp" /> 
 
 <textview 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:layout_gravity="center" 
 android:text="好友动态" 
 android:textcolor="#b8e7fe" 
 android:textsize="17sp" /> 
 
</framelayout>

          菜单栏包含一个返回按钮和一个标题,并且给菜单栏设置了固定高度和背景色,然后布局我们的activity_main.xml文件,代码如下:

<?xml version="1.0" encoding="utf-8"?> 
<framelayout xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:tools="http://schemas.android.com/tools" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent"> 
 
 <com.llew.wb.git.qqzone.flexiblelistview 
 android:id="@+id/flexible_list_view" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:scrollbars="none"></com.llew.wb.git.qqzone.flexiblelistview> 
 
 <include 
 android:id="@+id/custom_action_bar" 
 layout="@layout/action_bar_layout"/> 
</framelayout> 

        activity_main.xml的布局文件很简单,采用framelayout根布局让菜单栏悬浮在flexiblelistview上边,然后编写我们的mainactivity代码,如下所示:

public class mainactivity extends appcompatactivity { 
 
 private flexiblelistview mlistview; 
 
 @override 
 protected void oncreate(bundle savedinstancestate) { 
 super.oncreate(savedinstancestate); 
 setcontentview(r.layout.activity_main); 
 
 initglobalparams(); 
 } 
 
 private void initglobalparams() { 
 mlistview = (flexiblelistview) findviewbyid(r.id.flexible_list_view); 
 
 view mflexibleheaderview = new view(getapplicationcontext()); 
 mflexibleheaderview.setbackgroundcolor(color.parsecolor("#bbaacc")); 
 int height = getresources().getdimensionpixelsize(r.dimen.header_height); 
 layoutparams params = new layoutparams(layoutparams.match_parent, height); 
 mflexibleheaderview.setlayoutparams(params); 
 
 final view actionbar = findviewbyid(r.id.custom_action_bar); 
 
 mlistview.bindactionbar(actionbar); 
 mlistview.addheaderview(mflexibleheaderview); 
 
 mlistview.setadapter(new adapter()); 
 } 
 
 static class adapter extends baseadapter { 
 @override 
 public int getcount() { 
 return 80; 
 } 
 
 @override 
 public object getitem(int position) { 
 return null; 
 } 
 
 @override 
 public long getitemid(int position) { 
 return 0; 
 } 
 
 @override 
 public view getview(int position, view convertview, viewgroup parent) { 
 textview textview = new textview(parent.getcontext()); 
 textview.setpadding(50, 50, 50, 50); 
 textview.settext(position + 10 + ""); 
 return textview; 
 } 
 } 
} 

        在mainactivity中给flexiblelistview添加了一个固定高度背景色为"#bbaacc"的header,并把悬浮菜单栏actionbar赋值给了flexiblelistview的mactionbar,最后设置adapter,为了测试代码写的很简单,我们运行一下程序,看看效果:

        看到运行效果好开心呀,(*^__^*) ……透明度渐变功能达到了我们的预期,接下来开始实现阻尼效果,阻尼效果就是当listview滚动到了顶部此时若继续下滑,listview能够继续往下滚动一段距离当手指离开屏幕后listview要恢复原位置。为了实现这个功能有的童靴可能会想到重写有关事件传递的onxxxevent()等方法,之后在motionevent为down,move,up或者cancel条件下分别做逻辑判断来实现阻尼效果,此方式可行,但是和今天我们的实现相比起来复杂了许多......
        这里所实现阻尼效果所采用的方法是利用view的overscrollby()方法,有的童靴可能会问overscrollby()方法是2.3版本之后才增加的,2.3版本之前的兼容性怎么办?我实现这个功能之前也考虑过这个问题,一方面我们公司的app只支持3.0以上版本,另一方面2.3及以前的版本市场占有率几乎微乎其微了,所以可以考虑不再兼容2.3以前的老版本。
        有的同学或许对overscrollby()方法比较陌生,先大致说一下该方法,其源码如下:

/** 
 * scroll the view with standard behavior for scrolling beyond the normal 
 * content boundaries. views that call this method should override 
 * {@link #onoverscrolled(int, int, boolean, boolean)} to respond to the 
 * results of an over-scroll operation. 
 * 
 * views can use this method to handle any touch or fling-based scrolling. 
 * 
 * @param deltax change in x in pixels 
 * @param deltay change in y in pixels 
 * @param scrollx current x scroll value in pixels before applying deltax 
 * @param scrolly current y scroll value in pixels before applying deltay 
 * @param scrollrangex maximum content scroll range along the x axis 
 * @param scrollrangey maximum content scroll range along the y axis 
 * @param maxoverscrollx number of pixels to overscroll by in either direction 
 * along the x axis. 
 * @param maxoverscrolly number of pixels to overscroll by in either direction 
 * along the y axis. 
 * @param istouchevent true if this scroll operation is the result of a touch event. 
 * @return true if scrolling was clamped to an over-scroll boundary along either 
 * axis, false otherwise. 
 */ 
@suppresswarnings({"unusedparameters"}) 
protected boolean overscrollby(int deltax, int deltay, int scrollx, int scrolly, int scrollrangex, int scrollrangey, 
 int maxoverscrollx, int maxoverscrolly, boolean istouchevent) { 
 // ...... 
} 

        阅读源码看注释很重要,我们先看一下注释,大致意思如下:
        当view组件滚动到边界时还会继续进行之前的滚动操作(注意:没有滚动到边界时是不会触发该方法的),如果view组件调用了该方法那么view组件就应该重写onoverscrolled()方法来响应over-scroll操作。view控件可以调用该方法处理任何的触摸滚动或者是快速滑动等。感觉翻译的好别扭,说的直白点就是当listview,scrollview等滚动到头了若继续下滑就会调用该方法。
        overscrollby()方法有9个参数,每个参数注释都说的很详细,我们只看需要用到的俩参数deltay和istouchevent;deltay表示的是在y轴上滚动的相对值,比如listview滚动到了顶部此时如果继续下拉,deltay值为负数,当其滚动到了最底部当我们继续上拉,deltay值为正数,所以我们可以根据deltay判断listview是上拉操作还是下拉操作,istouchevent为true表示手指在触摸屏幕否则离开屏幕。
        了解overscrollby()方法后开始实现阻尼效果,核心就是重写overscrollby()方法,在该方法中动态改变headerview的高度,若手指松开我们就复原headerview。我们知道qq空间顶部是一张图片,当下拉的时候该图片有弹性拉升效果,当手指松开后图片又伸缩回去了,所以我们就直接用imageview模拟此效果。模拟图片阻尼可以让imageview的宽高为match_parent(headerview的高度改变之后imageview的高度也可以随之更改),这个时候还要设置imageview的scaletype为center_crop(不清楚imageview的scaletype属性可参照我之前写的一篇博文:android 源码系列之<一>从源码的角度深入理解imageview的scaletype属性)。
        现在开始在flexiblelistview中重写overscrollby()方法,代码如下:

@override 
protected boolean overscrollby(int deltax, int deltay, int scrollx, int scrolly, int scrollrangex, int scrollrangey, int maxoverscrollx, int maxoverscrolly, boolean istouchevent) { 
 if(null != mheaderview) { 
 if(istouchevent && deltay < 0) { 
 mheaderview.getlayoutparams().height += math.abs(deltay / 3.0); 
 mheaderview.requestlayout(); 
 } 
 } 
 return super.overscrollby(deltax, deltay, scrollx, scrolly, scrollrangex, scrollrangey, maxoverscrollx, maxoverscrolly, istouchevent); 
} 

        overscrollby()方法中我们根据deltay值动态的更改了mheaderview的高度并重新布局达到更改imageview高度的目的,注意:计算高度的时候用了deltay除以3,此时的3表示增长因子,目的是让headerview缓慢的增长,这里可以对外提供一个方法来设置此值。
        现在仅实现了headerview的拉升功能,但是还没有实现缩放功能,因为overscrollbay()中实现的是手指触摸的下拉,当手指离开屏幕后要进行headerview的复原操作,所以我们可以在考虑在ontouchevent()方法中判断motionevent的类型,当为up或者cancel时就复原headerview,复原headerview不能一下子复原而是要用动画的方式,这样看上去才比较自然,所以ontouchevent()代码如下:

@override 
public boolean ontouchevent(motionevent ev) { 
 if(null != mheaderview) { 
 int action = ev.getaction(); 
 if(motionevent.action_up == action || motionevent.action_cancel == action) { 
 resetheaderviewheight(); 
 } 
 } 
 return super.ontouchevent(ev); 
} 
 
private void resetheaderviewheight() { 
 valueanimator valueanimator = valueanimator.ofint(1); 
 valueanimator.setduration(700); 
 valueanimator.addupdatelistener(new valueanimator.animatorupdatelistener() { 
 @override 
 public void onanimationupdate(valueanimator animation) { 
 final float f = animation.getanimatedfraction(); 
 mheaderview.getlayoutparams().height -= f * (mheaderview.getlayoutparams().height - mmaxscrollheight); 
 mheaderview.requestlayout(); 
 
 } 
 }); 
 valueanimator.setinterpolator(new overshootinterpolator()); 
 valueanimator.start(); 
} 

        headerview的复原动画我们采用了valueanimator,当动画执行过程中我们动态的更改headerview的值来达到渐变效果。接下来布局headerview来模拟qq空间,代码如下:

<?xml version="1.0" encoding="utf-8"?> 
<framelayout xmlns:android="http://schemas.android.com/apk/res/android" 
 android:layout_width="match_parent" 
 android:layout_height="@dimen/header_height"> 
 
 <imageview 
 android:id="@+id/iv" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:scaletype="centercrop" 
 android:src="@mipmap/ttt" /> 
 
 <linearlayout 
 android:layout_width="match_parent" 
 android:layout_height="30dp" 
 android:layout_gravity="bottom" 
 android:background="#33333333" 
 android:gravity="center_vertical" 
 android:orientation="horizontal"> 
 
 <textview 
 android:layout_width="0dp" 
 android:layout_height="match_parent" 
 android:layout_weight="1" 
 android:text="相册" 
 android:gravity="center" 
 android:textcolor="@android:color/white" /> 
 
 <view 
 android:layout_width="1dp" 
 android:layout_height="20dp" 
 android:background="#ffffff" /> 
 
 <textview 
 android:layout_width="0dp" 
 android:layout_height="match_parent" 
 android:layout_weight="1" 
 android:text="说说" 
 android:gravity="center" 
 android:textcolor="@android:color/white" /> 
 
 <view 
 android:layout_width="1dp" 
 android:layout_height="20dp" 
 android:background="#ffffff" /> 
 
 <textview 
 android:layout_width="0dp" 
 android:layout_height="match_parent" 
 android:layout_weight="1" 
 android:text="个性化" 
 android:gravity="center" 
 android:textcolor="@android:color/white" /> 
 
 <view 
 android:layout_width="1dp" 
 android:layout_height="20dp" 
 android:background="#ffffff" /> 
 
 <textview 
 android:layout_width="0dp" 
 android:layout_height="match_parent" 
 android:layout_weight="1" 
 android:text="\@ 与我相关" 
 android:gravity="center" 
 android:textcolor="@android:color/white" /> 
 
 </linearlayout> 
</framelayout> 

        headerview的布局中让imageview的宽高都设置成了match_parent并且把scaletype设置为centercrop。修改mainactivity的initglobalparams()方法,代码如下:

void initglobalparams() { 
 mlistview = (flexiblelistview) findviewbyid(r.id.flexible_list_view); 
 view mflexibleheaderview = layoutinflater.from(this).inflate(r.layout.flexible_header_layout, mlistview, false); 
 abslistview.layoutparams params = (abslistview.layoutparams)mflexibleheaderview.getlayoutparams(); 
 if(null == params) { 
 params = new abslistview.layoutparams(abslistview.layoutparams.match_parent, abslistview.layoutparams.wrap_content); 
 } 
 params.height = getresources().getdimensionpixelsize(r.dimen.header_height); 
 mflexibleheaderview.setlayoutparams(params); 
 
 final view actionbar = findviewbyid(r.id.custom_action_bar); 
 
 mlistview.bindactionbar(actionbar); 
 mlistview.addheaderview(mflexibleheaderview); 
 
 mlistview.setadapter(new adapter()); 
} 

        ok,一切都准备就绪,赶紧运行一下程序,看看效果吧(*^__^*) ……

 恩,看上去效果还不错......
 好了,有关实现qq空间的阻尼下拉刷新和渐变菜单栏就结束了,主要是利用了2.3版本之后的overscrollby()方法(如果要兼容2.3之前版本需要童靴们自己去实现相关逻辑);其次充分的利用了imageview的scaletype属性来模拟了qq空间图片阻尼回弹的效果。再次感谢收看(*^__^*) ……

原文链接:

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网