本文同步自http://javaexception.com/archives/64

问题:

近期的需求中,碰到了一个view切换动画的需求。要实现的是点击按钮,从左到右滑动view,左边的view消失,右边的view出现。有点像文字跑马灯的效果,不过这次滚动的是view,具体看截图效果。

实现思路:

晚上在家写了一个比较low的实现方案,参考的思路是Banner轮播的思路,用viewPager来进行view的切换。大致效果也还行,只不过觉得代码量太多,使用比较麻烦。我就是想给两个view加上可以切换动画的效果,就要写那么多的代码,感觉不划算。只好放弃此方案。

随后想到了swipeView,发现这是一个挺好的点,可以从这里入手。经过对swipeMenuLayout代码的阅读分析以及测试实践。得出了以下的解决方案。

自定义SlideLayout.java

public class SlideLayout extends ViewGroup {
private static final String TAG = "SlideLayout";
private int mHeight;
private View mContentView;
private View mRightView;
private boolean isAnimation = false; public SlideLayout(Context context) {
this(context, null);
} public SlideLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
} public SlideLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
} @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//Log.d(TAG, "onMeasure() called with: " + "widthMeasureSpec = [" + widthMeasureSpec + "], heightMeasureSpec = [" + heightMeasureSpec + "]");
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mHeight = 0;
int contentWidth = 0;
int childCount = getChildCount(); final boolean measureMatchParentChildren = MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
boolean isNeedMeasureChildHeight = false; for (int i = 0; i < childCount; i++) {
View childView = getChildAt(i);
if (childView.getVisibility() != GONE) {
measureChild(childView, widthMeasureSpec, heightMeasureSpec);
final MarginLayoutParams lp = (MarginLayoutParams) childView.getLayoutParams();
mHeight = Math.max(mHeight, childView.getMeasuredHeight()/* + lp.topMargin + lp.bottomMargin*/);
if (measureMatchParentChildren && lp.height == LayoutParams.MATCH_PARENT) {
isNeedMeasureChildHeight = true;
}
if (i == 0) {
mContentView = childView;
contentWidth = childView.getMeasuredWidth();
} else {
mRightView = childView;
}
}
}
setMeasuredDimension(getPaddingLeft() + getPaddingRight() + contentWidth,
mHeight + getPaddingTop() + getPaddingBottom());//宽度取第一个Item(Content)的宽度
if (isNeedMeasureChildHeight) {//如果子View的height有MatchParent属性的,设置子View高度
forceUniformHeight(childCount, widthMeasureSpec);
}
} @Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new MarginLayoutParams(getContext(), attrs);
} /**
* 给MatchParent的子View设置高度
*
* @param count
* @param widthMeasureSpec
* @see android.widget.LinearLayout# 同名方法
*/
private void forceUniformHeight(int count, int widthMeasureSpec) {
// Pretend that the linear layout has an exact size. This is the measured height of
// ourselves. The measured height should be the max height of the children, changed
// to accommodate the heightMeasureSpec from the parent
int uniformMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(),
MeasureSpec.EXACTLY);//以父布局高度构建一个Exactly的测量参数
for (int i = 0; i < count; ++i) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
if (lp.height == LayoutParams.MATCH_PARENT) {
// Temporarily force children to reuse their old measured width
int oldWidth = lp.width;//measureChildWithMargins 这个函数会用到宽,所以要保存一下
lp.width = child.getMeasuredWidth();
// Remeasure with new dimensions
measureChildWithMargins(child, widthMeasureSpec, 0, uniformMeasureSpec, 0);
lp.width = oldWidth;
}
}
}
} @Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
//Log.e(TAG, "onLayout() called with: " + "changed = [" + changed + "], l = [" + l + "], t = [" + t + "], r = [" + r + "], b = [" + b + "]");
int childCount = getChildCount();
int left = 0 + getPaddingLeft();
for (int i = 0; i < childCount; i++) {
View childView = getChildAt(i);
if (childView.getVisibility() != GONE) {
if (i == 0) {//第一个子View是内容 宽度设置为全屏
childView.layout(left, getPaddingTop(), left + childView.getMeasuredWidth(), getPaddingTop() + childView.getMeasuredHeight());
left = left + childView.getMeasuredWidth();
} else {
childView.layout(left, getPaddingTop(), left + childView.getMeasuredWidth(), getPaddingTop() + childView.getMeasuredHeight());
left = left + childView.getMeasuredWidth();
}
}
}
//Log.d(TAG, "onLayout() called with: " + "maxScrollGap = [" + maxScrollGap + "], l = [" + l + "], t = [" + t + "], r = [" + r + "], b = [" + b + "]");
} public void slideLeft(long duration) {
if (isAnimation) {
return;
}
AnimatorSet animatorSet = new AnimatorSet();
final ObjectAnimator objectAnimator1 = ObjectAnimator.ofFloat(mContentView, "translationX", 0, -mContentView.getMeasuredWidth());
final ObjectAnimator objectAnimator2 = ObjectAnimator.ofFloat(mRightView, "translationX", 0, -mContentView.getMeasuredWidth());
animatorSet.playTogether(objectAnimator1, objectAnimator2);
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
super.onAnimationStart(animation);
isAnimation = true;
} @Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
isAnimation = false;
}
});
animatorSet.setDuration(duration);
animatorSet.start();
} public void slideRight(long duration) {
if (isAnimation) {
return;
}
AnimatorSet animatorSet = new AnimatorSet();
final ObjectAnimator objectAnimator1 = ObjectAnimator.ofFloat(mContentView, "translationX", -mContentView.getMeasuredWidth(), 0);
final ObjectAnimator objectAnimator2 = ObjectAnimator.ofFloat(mRightView, "translationX", -mContentView.getMeasuredWidth(), 0);
animatorSet.playTogether(objectAnimator1, objectAnimator2);
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
super.onAnimationStart(animation);
isAnimation = true;
} @Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
isAnimation = false;
}
});
animatorSet.setDuration(duration);
animatorSet.start();
}
}

接着看看如何使用,调用方式。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity"> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"> <Button
android:id="@+id/btn_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="向左滑动" /> <Button
android:id="@+id/btn_start2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="向右滑动" />
</LinearLayout> <me.star.animator.SlideLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal"> <TextView
android:id="@+id/btn_show"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorAccent"
android:padding="4dp"
android:text="展示1"
android:textSize="20sp"
android:visibility="visible" /> <TextView
android:id="@+id/btn_show2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/holo_green_light"
android:padding="4dp"
android:text="展示2"
android:textSize="20sp" /> </me.star.animator.SlideLayout> </LinearLayout>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShow = findViewById(R.id.btn_show);
btnShow2 = findViewById(R.id.btn_show2);
btnStart = findViewById(R.id.btn_start);
btnStart2 = findViewById(R.id.btn_start2);
container = findViewById(R.id.container); btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
container.slideLeft(3000);
}
}); btnStart2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
container.slideRight(3000);
}
});
}

其他相关:

看到泡网上有一个为View和Activity设置左右切换动画的文章http://www.jcodecraeer.com/a/basictutorial/2016/1014/6672.html

代码下载:

链接:https://pan.baidu.com/s/1Tg7-eJYSOZqEGU-fQY4how 密码:c8q8

为View设置左右切换动画的更多相关文章

  1. Android 编程下设置 Activity 切换动画

    为 Activity 设置切换动画 我们知道,我们可以在 AndroidManifest.xml 文件中,通过 android:theme 属性设置 Activity 的主题.主题中定义了关于 Act ...

  2. Swift:超炫的View Controller切换动画

    匿名社交应用Secret的开发者开发了一款叫做Ping的应用,用户可以他们感兴趣的话题的推送. Ping有一个很炫的东西,就是主界面和之间切换的动画做的非常的好.每次看到一个非常炫的动画,都不由得会想 ...

  3. Android 动画之View动画效果和Activity切换动画效果

    View动画效果: 1.>>Tween动画通过对View的内容进行一系列的图形变换(平移.缩放.旋转.透明度变换)实现动画效果,补间动画需要使用<set>节点作为根节点,子节点 ...

  4. Activity切换动画。从右边滑入,关闭时从左边滑入

    直接贴代码吧   1. 动画文件(两个动画文件配置到res/anim目录下) activity_anim_in_right.xml <?xml version="1.0" e ...

  5. activity添加切换动画之后出现的黑色背景问题

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">     & ...

  6. Android Listview切换动画,扩展到任意view切换之间动画实现

    添加布局如下: <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2010 ...

  7. 解决Activity启动黑屏和设置android:windowIsTranslucent不兼容activity切换动画的问题

    在该项目中遇到开Activity之后,黑屏问题,解决的办法是在网上通过设置发现theme和style特性,可以实现. http://www.cnblogs.com/sunzn/p/3407078.ht ...

  8. Activity 设置切换动画

    extends://blog.csdn.net/luohaowang320/article/details/42124225 | http://blog.csdn.net/xuewater/artic ...

  9. Android Activity 切换动画(非原创)

    在Android开发过程中,经常会碰到Activity之间的切换效果的问题,下面介绍一下如何实现左右滑动的切换效果,首先了解一下Activity切换的实现,从Android2.0开始在Activity ...

随机推荐

  1. 2017年的golang、python、php、c++、c、java、Nodejs性能对比[续]

    2017年的golang.python.php.c++.c.java.Nodejs性能对比[续] 最近忙,这个话题放了几天,今天来个续集.   上篇传送门: 2017年的golang.python.p ...

  2. sql server 高可用故障转移(2)

    添加网卡心跳线 目标: 二台sql服务器需要添加网卡心跳线,用于sql server内部数据传输 计算机名 Ip信息 心跳线 Hsr1 192.168.2.50    (ipv4 ip) 255.25 ...

  3. 解决Debian 9 iwlwifi固件缺失导致无法连接无线网络的问题

    本文由荒原之梦原创,原文链接:http://zhaokaifeng.com/?p=692 前言: 本文介绍了解决Debian9安装完成后无法连接wifi的问题以及一些扩展知识. 问题描述: 安装Deb ...

  4. Spring Boot工程支持HTTP和HTTPS,HTTP重定向HTTPS

    本文试图以通俗易通的方式介绍Https的工作原理,不纠结具体的术语,不考证严格的流程.我相信弄懂了原理之后,到了具体操作和实现的时候,方向就不会错,然后条条大路通罗马.阅读文本需要提前大致了解对称加密 ...

  5. BOM(浏览器对象模型)

    .t1 { background-color: #ff8080; width: 1100px; height: 40px } 一.BOM(浏览器对象模型) 1.screen对象. console.lo ...

  6. 你不知道的JavaScript--Item18 JScript的Bug与内存管理

    1.JScript的Bug IE的ECMAScript实现JScript严重混淆了命名函数表达式,搞得现很多人都出来反对命名函数表达式,而且即便是现在还一直在用的一版(IE8中使用的5.8版)仍然存在 ...

  7. Asp.Net WebAPI中Filter过滤器的使用以及执行顺序

    转发自:http://www.cnblogs.com/UliiAn/p/5402146.html 在WEB Api中,引入了面向切面编程(AOP)的思想,在某些特定的位置可以插入特定的Filter进行 ...

  8. 比较集合List<T>集合,前后多了哪些数据,少了哪些数据Except

    1.少了哪些数据 private List<int> GetRoleIdListReduce(List<int> roleIdListOld, List<int> ...

  9. client.go

    package)*time.Second) ], {         hasConn := false         waitc := time.After(cfg.DialTimeout)     ...

  10. 【线段树】Bzoj1230 [Usaco2008 Nov]lites 开关灯

    Description Farmer John尝试通过和奶牛们玩益智玩具来保持他的奶牛们思维敏捷. 其中一个大型玩具是牛栏中的灯. N (2 <= N <= 100,000) 头奶牛中的每 ...