Android实现双向滑动特效的实例代码

  

记得在很早之前,我写了一篇关于Android滑动菜单的文章,其中有一个朋友在评论中留的言,希望我可以帮他将这个滑动菜单改成双向滑动的方式。当时也没想花太多时间,简单修改了一下就发给了他,结果没想到后来却有一大批的朋友都来问我要这份双向滑动菜单的代码。由于这份代码写得很不用心,我发了部分朋友之后实在不忍心继续发下去了,于是决定专门写一篇文章来介绍更好的Android双向滑动菜单的实现方法。

  

在开始动手之前先来讲一下实现原理,在一个活动的布局中需要有三部分,一个是左侧菜单的布局,一个是右侧菜单的布局,一个是内容布局。左侧菜单居屏幕左边缘对齐,右侧菜单居屏幕右边缘对齐,然后内容布局占满整个屏幕,并压在了左侧菜单和右侧菜单的上面。当用户手指向右滑动时,将右侧菜单隐藏,左侧菜单显示,然后通过偏移内容布局的位置,就可以让左侧菜单展现出来。同样的道理,当用户手指向左滑动时,将左侧菜单隐藏,右侧菜单显示,也是通过偏移内容布局的位置,就可以让右侧菜单展现出来。原理示意图所下所示:

  

 Android实现双向滑动特效的实例代码

  

介绍完了原理,我们就开始动手实现吧。新建一个Android项目,项目名就叫做BidirSlidingLayout。然后新建我们最主要的BidirSlidingLayout类,这个类就是实现双向滑动菜单功能的核心类,代码如下所示:

        公共类BidirSlidingLayout扩展RelativeLayout实现>   & lt; com.example.bidirslidinglayout。BidirSlidingLayout xmlns: android=" http://schemas.android.com/apk/res/android "   xmlns:工具=" http://schemas.android.com/tools "   android: id=癅 + id/bidir_sliding_layout”   android: layout_width="宽和"   android: layout_height=翱砗汀北?   & lt;使用   android: id=癅 + id/left_menu”   android: layout_width=" 270下降”   android: layout_height="宽和"   android: layout_alignParentLeft=" true "   android:背景=" # 00 ccff”   android:可见性=耙巍北?   & lt; TextView   android: layout_width=" wrap_content "   android: layout_height=" wrap_content "   android: layout_centerInParent=" true "   android:文本="这是左菜单”   android:输入textColor=" # 000000 "   android: textSize=" 28 sp "/比;   & lt;/RelativeLayout>   & lt;使用   android: id=癅 + id/right_menu”   android: layout_width=" 270下降”   android: layout_height="宽和"   android: layout_alignParentRight=" true "   android:背景=" # 00物品”   android:可见性=耙巍北?   & lt; TextView   android: layout_width=" wrap_content "   android: layout_height=" wrap_content "   android: layout_centerInParent=" true "   android:文本="这是正确的菜单"   android:输入textColor=" # 000000 "   android: textSize=" 28 sp "/比;   & lt;/RelativeLayout>   LinearLayout & lt;   android: id=癅 + id/内容”   android: layout_width=" 320下降”   android: layout_height="宽和"   android:背景=" # e9e9e9”比;   & lt;列表视图   android: id=癅 + id/contentList”   android: layout_width="宽和"   android: layout_height="宽和"   android:滚动条="没有"   android: cacheColorHint=" # 00000000 "比;   & lt;/ListView>   & lt;/LinearLayout>   & lt;/com.example.bidirslidinglayout.BidirSlidingLayout>之前      

,可以看的到,我们使用了自定义的BidirSlidingLayout作为根布的局,然后依次加入了三个子布局分别作为左侧菜单,右侧菜单和内容的布局。左侧菜单和右侧菜单中都只是简单地放入了一个TextView用于显示一段文字,内容布局中放入了一个ListView。注意要让左侧菜单和父布局左边缘对齐,右侧菜单和父布局右边缘对齐。

  

最后打开或者创建MainActivity作为程序的主活动,代码如下所示:

        公开课MainActivity延伸活动{/* *   *双向滑动菜单布的局   */私人BidirSlidingLayout bidirSldingLayout;/* *   *在内容布局上显示的列表视图   */私人ListView contentList;/* *   * ListView的适配器   */私人ArrayAdaptercontentListAdapter;/* *   *用于填充contentListAdapter的数据源。   */私人String [] contentItems={"内容项1”,“内容项2”,3”“内容项,   “内容项4”、“内容项5”,“内容项6”,“内容项7”,   “内容项8”,“内容项9”、“内容项10”,“内容项11”,   “内容项12”,“内容项13”,“内容项14”、“内容项15”,   "内容项16 "};   @Override   保护无效alt=" Android实现双向滑动特效的实例代码">

Android实现双向滑动特效的实例代码