前几天在github上看到一个DrawableLayout的项目,地址:https://github.com/Yalantis/Side-Menu.Android,感觉效果很不错,以后可以用到自己的项目中,于是对项目进行了仿写,并没有使用DrawableLayout,而是自己定义了一个LinearLayout,向其中添加按钮,点击按钮后进行页面的切换,具体效果如下所示:
看结果还是挺不错的,以下是源码分析,在编写过程中,借鉴了github上面的代码。
1、动画效果
在侧边栏弹出的时候,我们看到了一个翻转的动画效果,以y轴为翻转轴,菜单依次翻转弹出,我们需要定义一个FlipAnimation,继承Animation,实现翻转效果,代码如下:
/**
* 3d变化动画,实现了View绕Y轴旋转的效果,来源于开源控件Yalantis/Side-Menu.Android
* 地址 https://github.com/Yalantis/Side-Menu.Android
* Created by Konstantin on 22.12.2014.
*/
public class FlipAnimation extends Animation {
private final float mFromDegrees;
private final float mToDegrees;
private final float mCenterX;
private final float mCenterY;
private Camera mCamera;
public FlipAnimation(float fromDegrees, float toDegrees, float centerX, float centerY) {
mFromDegrees = fromDegrees;
mToDegrees = toDegrees;
mCenterX = centerX;
mCenterY = centerY;
}
@Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
mCamera = new Camera();
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final float fromDegrees = mFromDegrees;
float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);
final float centerX = mCenterX;
final float centerY = mCenterY;
final Camera camera = mCamera;
final Matrix matrix = t.getMatrix();
camera.save();
camera.rotateY(degrees);
camera.getMatrix(matrix);
camera.restore();
matrix.preTranslate(-centerX, -centerY);
matrix.postTranslate(centerX, centerY);
}
}
主要就是通过矩阵变换,实现动画效果,改变这个类,我们可以实现自定义动画效果。
2、侧边菜单动画效果
有了动画效果后,需要将动画效果运用在侧边菜单上,定义ViewAnimator,代码如下:
/**
* View动画
* Created by dingxiaolei on 16/4/1.
*/
public class ViewAnimator {
private final int ANIMATION_DURATION = 175;
private Activity activity;
private List<MenuItemBean> list = new ArrayList<>();
private List<View> viewList = new ArrayList<>();
<