做Android开发,经常会碰到仿照IOS实现某种功能的需求。每当碰到这种需求的时候,我其实很抵触的。类似滑动删除的需求更是家常便饭。比如微信、QQ的会话列表都是有滑动删除的功能,Android也有比较成熟的开源项项目SwipeListview来实现列表的滑动删除功能。前不久,碰到一个需求是某个布局带滑动删除的功能。正好以前有读过某大神的博文高仿微信对话列表滑动删除效果,所以本文实现在其基础上加以改进。
最终要实现效果如下。
大家有兴趣可以先读下高仿微信对话列表滑动删除效果,了解其核心思想。我这边主要是基于该文解决某些事件冲突和bug。
接着来分析SwipeLayout的具体实现。
1.SwipeLayout所需布局container_swipelayout.xml
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:id="@+id/view_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
<RelativeLayout
android:id="@+id/view_right"
android:layout_width="120dp"
android:layout_height="match_parent"
android:clickable="true" >
</RelativeLayout>
</merge>
这里我把SwipeLayout的布局分为两个部分,view_content用于加载上面效果图的黄色区域,view_right用于加载红色区域。这样区分的好处是我们可以实现任何你想要的效果了。
接着来看SwipeLayout的代码实现,在代码注释中,已经说明如何解决事件冲突。