先来看下面的这张效果图:
上面这张效果图是百度影音的,现在在Android上很流行,最初是由facebook自己实现的,而后各大应用有跟风之势,那么这种侧滑效果是如何实现的呢?
网上现在这种侧滑菜单的例子很对,也有开源的框架sliderMenu,而且可以定义很多样式,但大部分例子,都只是实现了这种类似效果,没有实现一种可移植的框架,仅仅是单页面效果而已,而且集成起来复杂,鉴于此,我自己实现了一套侧滑菜单的框架:
1、最常用的支持左右策划
2、多个页面切换也好不费力,页面切换的逻辑已经实现好了,集成进来,只需要关注自己项目的业务逻辑
3、支持多个页面集成
4、支持退出业务逻辑
先上我自己实现的效果图:
下面 说一下实现原理:
布局文件采用FrameLayout, 在一个FrameLayout下有二个子布局,一个是菜单,另一个是LeftSliderLayout,而LeftSliderLayout下面可以放二个子布局:第一个是阴影布局(左边阴影),第二个是要拖动的内容。,当向右拖动LeftSliderLayout时,就显示露出菜单布局。而向左拖动LeftSliderLayout时,就覆盖菜单布局。
1.FrameLayout的布局文件local_media_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<include android:id="@+id/main_layout_below" layout="@layout/main_layout_below" />
<com.zhaoxufeng.leftsliderlayout.lib.LeftSliderLayout
android:id="@+id/main_slider_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<!-- Shadow Child -->
<ImageView
android:layout_width="15px"
android:layout_height="fill_parent"
android:contentDescription="@null"
android:scaleType="fitXY"
android:src="@drawable/main_side_shadow" />
<!-- Main Child -->
<include android:id="@+id/main_slider_main" layout="@layout/local_media" />
</com.zhaoxufeng.leftsliderlayout.lib.LeftSliderLayout>
</FrameLayout>
上面 xml 中main_layout_below是对应的左边菜单Menu布局文件(这个布局文件是固定的),local_media是你要的拖动布局
2、LeftSliderLayout.java代码
package com.zhaoxufeng.leftsliderlayout.lib;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Scroller;
public class LeftSliderLayout extends ViewGroup {
private static final String TAG = "LeftSliderLayout" ;
private Scroller mScroller;
private VelocityTracker mVelocityTracker;
/**
* Constant value for touch state
* TOUCH_STATE_REST : no touch
* TOUCH_STATE_SCROLLING : scrolling
*/
private static final int TOUCH_STATE_REST = 0;
private static final int TOUCH_STATE_SCROLLING = 1;
private int mTouchState = TOUCH_STATE_REST;
/**
* Distance in pixels a touch can wander before we think the user is scrolling
*/
private int mTouchSlop;
/**
* Values for saving axis of the last touch event.
*/
private float mLastMotionX;
private float mLastMotionY;
/**
* Values for VelocityTracker to compute current velocity.
* VELOCITY_UNITS in dp
* mVelocityUnits in px
*/
private static final int VELOCITY_UNITS = 1000;
private int mVelocityUnits;
/**
* The minimum velocity for determining the direction.
* MINOR_VELOCITY in dp
* mMinorVelocity in px
*/
private static final float MINOR_VELOCITY = 150.0f;
private int mMinorVelocity;
/**
* The width of Sliding distance from left.
* And it should be the same with the width of t