android 自定义ScrollView实现背景图片伸缩的实现代码及思路

首先还是按照惯例给大家看下示例.

     

用过多米音乐的都会知道, 这个UI可以上下滑动,作用嘛---无聊中可以划划解解闷,这被锤子公司老罗称呼为“情怀”,其实叫“情趣”更合适。嘿嘿.如今移动互联网发展这么迅速,市场上已不再是那初期随便敲个APP放上架就能拥有几十万用户的阶段了.最近苹果公司,为了怕android下载量赶超苹果商店,大势声称:(第 500 亿个下载应用的用户就可以获得 10,000 美元的 iTunes 礼品卡,除此之外,紧随第 500 亿之后的前 50 名用户也可以获得 500 美元的礼品卡.至于移动发展趋势,我想搞移动IT的人心里都比较清楚,扯远了).应用UI特效是应用中很大的一部分,如果同样功能的两款软件,一个功能好点如“网易新闻”,另外一个稍微差点如“新浪新闻”,用户的你毫无疑问肯定会选择网易客户端.总结就是“操作性”对于产品起着至关重要的因素.

接下来我们看下如何实现,首先声明,这个实现的方式不是很好,我这里只是提出一个解决方案,大家可以根据自己的想法进行创新.

原理:RelativeLayout+自定义ScrollView.

我们大致看下布局结构如图:

             

其实也没什么技术含量,我简单介绍下:红色代表的是背景照片,绿色的代表自定义ScrollView,粉色是代表你要编辑的透明区域.也不过多解释,想必大家都明白,我们还是来看代码吧。

由于属于情怀特效(没有具体的回调事件要求),那么就没有必要自定义监听,回调处理,我直接把要处理的UI注入到自定义控件中,这样她方便我也方便.

在此说明一下,前面部分实现中有误,但是也希望您仔细品读,相信您一定可以学到一些知识的。


首先我们将背景图片和顶部线条注入到该控件中。接着我们看onTouchEvent事件,因为至始至终都是她在起作用.

[java]  view plain copy
  1. /*** 
  2.      * 触摸事件 
  3.      *  
  4.      * @param ev 
  5.      */  
  6.     public void commOnTouchEvent(MotionEvent ev) {  
  7.         int action = ev.getAction();  
  8.         switch (action) {  
  9.         case MotionEvent.ACTION_DOWN:  
  10.             initTouchY = ev.getY();  
  11.   
  12.             current_Top = initTop = imageView.getTop();  
  13.             current_Bottom = initBottom = imageView.getBottom();  
  14.             lineUp_current_Top = line_up_top = line_up.getTop();  
  15.             lineUp_current_Bottom = line_up_bottom = line_up.getBottom();  
  16.             break;  
  17.         case MotionEvent.ACTION_UP:  
  18.             /** 回缩动画 **/  
  19.             if (isNeedAnimation()) {  
  20.                 animation();  
  21.             }  
  22.   
  23.             isMoveing = false;  
  24.             touchY = 0;// 手指松开要归0.  
  25.   
  26.             break;  
  27.   
  28.         /*** 
  29.          * 排除出第一次移动计算,因为第一次无法得知deltaY的高度, 然而我们也要进行初始化,就是第一次移动的时候让滑动距离归0. 
  30.          * 之后记录准确了就正常执行. 
  31.          */  
  32.         case MotionEvent.ACTION_MOVE:  
  33.   
  34.             Log.e(TAG, "isMoveing=" + isMoveing);  
  35.   
  36.             touchY = ev.getY();  
  37.   
  38.             float deltaY = touchY - initTouchY;// 滑动距离  
  39.   
  40.             Log.e(TAG, "deltaY=" + deltaY);  
  41.   
  42.             /** 过滤: **/  
  43.             if (deltaY < 0 && inner.getTop() <= 0) {  
  44.                 return;  
  45.             }  
  46.   
  47.             // 当滚动到最上或者最下时就不会再滚动,这时移动布局  
  48.             isNeedMove();  
  49.   
  50.             if (isMoveing) {  
  51.                 // 初始化头部矩形  
  52.                 if (normal.isEmpty()) {  
  53.                     // 保存正常的布局位置  
  54.                     normal.set(inner.getLeft(), inner.getTop(),  
  55.                             inner.getRight(), inner.getBottom());  
  56.                 }  
  57.                 // 移动布局(手势移动的1/3)  
  58.                 float inner_move_H = deltaY / 5;  
  59.                 inner.layout(normal.left, (int) (normal.top + inner_move_H),  
  60.                         normal.right, (int) (normal.bottom + inner_move_H));  
  61.   
  62.                 /** image_bg **/  
  63.                 float image_move_H = deltaY / 10;  
  64.                 current_Top = (int) (initTop + image_move_H);  
  65.                 current_Bottom = (int) (initBottom + image_move_H);  
  66.                 imageView.layout(imageView.getLeft(), current_Top,  
  67.                         imageView.getRight(), current_Bottom);  
  68.   
  69.                 /** line_up **/  
  70.                 float line_up_H = inner_move_H;  
  71.                 lineUp_current_Top = (int) (line_up_top + inner_move_H);  
  72.                 lineUp_current_Bottom = (int) (line_up_bottom + inner_move_H);  
  73.                 line_up.layout(line_up.getLeft(), lineUp_current_Top,  
  74.                         line_up.getRight(), lineUp_current_Bottom);  
  75.             }  
  76.             break;  
  77.   
  78.         default:  
  79.             break;  
  80.   
  81.         }  
  82.     }  
简单说明:

 MotionEvent.ACTION_DOWN:触摸摁下获取相应的坐标.

MotionEvent.ACTION_MOVE:

里面有个方法isNeedMove。作用:我们滑动的是ScrollView自身呢,还是我们自己模拟的那种滑动.

[java]  view plain copy
  1. /*** 
  2.      * 是否需要移动布局 inner.getMeasuredHeight():获取的是控件的总高度 
  3.      *  
  4.      * getHeight():获取的是屏幕的高度 
  5.      *  
  6.      * @return 
  7.      */  
  8.     public void isNeedMove() {  
  9.         int offset = inner.getMeasuredHeight() - getHeight();  
  10.         int scrollY = getScrollY();  
  11.         // 如果ScrollView的子View们没有超过一屏幕则scrollY == 0,直接返回true,  
  12.         //如果ScrollView的子View们超过了一屏幕则 getScrollY()==offset说明滑到了ScrollView的低端.这时候才返回true.  
  13.         if (scrollY == 0 || scrollY == offset) {  
  14.             isMoveing = true;  
  15.         }  
  16.     }  
这里面用到最多的就是:view.layout(l, t, r, b);作用很简单不解释。详情请参看源码.

 MotionEvent.ACTION_UP:就是做些善后操作,主要看animation方法.

[java]  view plain copy
  1. /*** 
  2.      * 回缩动画 
  3.      */  
  4.     public void animation() {  
  5.   
  6.         TranslateAnimation image_Anim = new TranslateAnimation(00,  
  7.                 Math.abs(initTop - current_Top), 0);  
  8.         image_Anim.setDuration(200);  
  9.         imageView.startAnimation(image_Anim);  
  10.   
  11.         imageView.layout(imageView.getLeft(), (int) initTop,  
  12.                 imageView.getRight(), (int) initBottom);  
  13.   
  14.         // 开启移动动画  
  15.         TranslateAnimation inner_Anim = new TranslateAnimation(00,  
  16.                 inner.getTop(), normal.top);  
  17.         inner_Anim.setDuration(200);  
  18.         inner.startAnimation(inner_Anim);  
  19.         inner.layout(normal.left, normal.top, normal.right, normal.bottom);  
  20.   
  21.         /** line_up **/  
  22.         TranslateAnimation line_up_Anim = new TranslateAnimation(00,  
  23.                 Math.abs(line_up_top - lineUp_current_Top), 0);  
  24.         line_up_Anim.setDuration(200);  
  25.         line_up.startAnimation(line_up_Anim);  
  26.         line_up.layout(line_up.getLeft(), line_up_top, line_up.getRight(),  
  27.                 line_up_bottom);  
  28.   
  29.         normal.setEmpty();  
  30.   
  31.         /** 动画执行 **/  
  32.         if (current_Top > initTop + 50 && turnListener != null)  
  33.             turnListener.onTurn();  
  34.   
  35.     }  
这里我要简单说明一下,因为我在这里栽了有些时间.

比如:我们的背景图片原先坐标为:(0,-190,800,300),随着手势移动到(0,-100,800,390)移动了90像素,那么我们的TranslateAnimation应该如何写呢?我之前总认为不就是末尾坐标指向初始坐标不就完了,结果你会发现,动画根本不起作用而是一闪而过。原因呢,动画参数不可以为负数.或许因为动画是以(0,0)为参照物吧.因此要把动画写成TranslateAnimation line_up_Anim = new TranslateAnimation(0, 0,Math.abs(-190- (-100)), 0);这样我们所需要的动画效果就实现了.

但是新的问题又出现了:

当你下拉到一定状态后然后慢慢向上移动,会发现移动的很快(没有回缩的反应),而移动到最顶部的时候突然又出现反弹效果。这个效果固然不是我们所需要的那种。我们所需要的效果是:下拉到一定程度,然后反过来上拉的时候要慢慢的移动回到原点(中心位置)停止。如果是上拉的话,不要出现反弹效果,如果是下拉松开的话,出现反弹效果。

描述的有点乱,如果想知道具体效果的话,我建议你使用下papa,其实国内这些比较优秀的应用UI都是抄袭国外的,如果你用facebook的话,就会发现,怎么啪啪的个人页面长的也忒像facebook了。请看下图:

       

嘿嘿,不好意思,跑题了,针对上面出现的问题,我简单说明一下.

首先,比如我们手势下拉了50像素,其实是使得自定义ScrollView的孩子也就是LinearLayout这个控件的top为50,而这个时候的getScrollY()的值仍为0,但是如果此时你停止下拉反而向上拉取的话,那么此时的getScrollY()会从0开始逐渐增大,当我们移动到顶部也就是将ScrollView移动到最底部,此时的isMoveing为true,所以你继续上拉的话会出现反弹效果。

这个问题要如何解决呢,其实也不难,但是我纠结了好长时间,也走了好多弯路。在这里说明一下我的瞎跑路段以及疑问:当时我就想,getScrollY()这么不听话,我何必非要对ScrollView的孩子进行操作呢,为何直接不对本控件执行layout(l,t,r,b)呢,后来就照着这个逻辑进行update,终于更改了差不多了,纠结了问题再次出现,在你下拉的时候对ScrollView本身执行layout(l,t,r,b)这个方法可以实现反弹效果,但是此时你确无法进行滑动了,就是ScrollView本身的滑动无缘无故的被禁止掉了.我怀疑是layout的时候参数弄错了。,后来仔细修改了下发现还是不可以滑动,然后google了半天也杳无音讯,最后固然放弃,又回到了原点。接着琢磨。。。算是功夫不负有心人吧,最终想到了解决方案,希望对您有帮助。

还拿上面说到的那短话,比如我们手势下拉了50像素,那么此时touch的距离也就是50像素,如果此时我们反向上拉的话,同样是需要50像素回到最初的位置。说到这里我想大家都明白了。(首先我们要将操作分开,分为UP,DOWN,如果是DOWN的话,那么在下拉后执行上拉的时候我们禁用掉自定义控件的滑动,而是通过手势执行layout执行这50像素.)

下面我们看部分代码:

[java]  view plain copy
  1. /**对于首次Touch操作要判断方位:UP OR DOWN**/  
  2.             if (deltaY < 0 && state == state.NOMAL) {  
  3.                 state = State.UP;  
  4.             } else if (deltaY > 0 && state == state.NOMAL) {  
  5.                 state = State.DOWN;  
  6.             }  
  7.   
  8.   
  9.             if (state == State.UP) {  
  10.                 deltaY = deltaY < 0 ? deltaY : 0;  
  11.                 isMoveing = false;  
  12.                 shutTouch = false;  
  13.             } else if (state == state.DOWN) {  
  14.                 if (getScrollY() <= deltaY) {  
  15.                     shutTouch = true;  
  16.                     isMoveing = true;  
  17.                 }  
  18.                 deltaY = deltaY < 0 ? 0 : deltaY;  
  19.             }  

代码很简单,不过多解释了,不明白的话,仔细看下源码肯定就明白了。


touch 事件处理:

[java]  view plain copy
  1. /** touch 事件处理 **/  
  2.     @Override  
  3.     public boolean onTouchEvent(MotionEvent ev) {  
  4.         if (inner != null) {  
  5.             commOnTouchEvent(ev);  
  6.         }  
  7.         // ture:禁止控件本身的滑动.  
  8.         if (shutTouch)  
  9.             return true;  
  10.         else  
  11.             return super.onTouchEvent(ev);  
  12.   
  13.     }  

说明:如果返回值为true,作用:禁止ScrollView的滑动,此时的Touch事件还存哦!!!如果对Touch事件比较熟悉的同学,相信觉得我有点废话了,哈哈,我也是个小菜鸟,也卡在这里过。


最后呢,还有个小BUG,也就是那个顶部拉线,如果你让ScrollView惯性滑动的话,那么你会发现,顶部线条没有跟随移动,其实就是因为惯性滑动的时候我们是获取不到getScrollY()的值得造成的,查了半天也没有找到相关资料,这个问题就暂时就留在这里,有时间了在续。


这里我将源码贴出来:

[java]  view plain copy
  1. package com.example.scrollviewdemo;  
  2.   
  3. import android.content.Context;  
  4. import android.graphics.Rect;  
  5. import android.util.AttributeSet;  
  6. import android.util.Log;  
  7. import android.view.MotionEvent;  
  8. import android.view.View;  
  9. import android.view.animation.TranslateAnimation;  
  10. import android.widget.ImageView;  
  11. import android.widget.ScrollView;  
  12.   
  13. /** 
  14.  * 自定义ScrollView 
  15.  *  
  16.  * @author jia 
  17.  *  
  18.  */  
  19. public class PersonalScrollView extends ScrollView {  
  20.   
  21.     private final String TAG = PersonalScrollView.class.getSimpleName();  
  22.   
  23.     private View inner;// 孩子View  
  24.   
  25.     private float touchY;// 点击时Y坐标  
  26.   
  27.     private float deltaY;// Y轴滑动的距离  
  28.   
  29.     private float initTouchY;// 首次点击的Y坐标  
  30.   
  31.     private boolean shutTouch = false;// 是否关闭ScrollView的滑动.  
  32.   
  33.     private Rect normal = new Rect();// 矩形(这里只是个形式,只是用于判断是否需要动画.)  
  34.   
  35.     private boolean isMoveing = false;// 是否开始移动.  
  36.   
  37.     private ImageView imageView;// 背景图控件.  
  38.     private View line_up;// 上线  
  39.     private int line_up_top;// 上线的top  
  40.     private int line_up_bottom;// 上线的bottom  
  41.   
  42.     private int initTop, initBottom;// 初始高度  
  43.   
  44.     private int current_Top, current_Bottom;// 拖动时时高度。  
  45.   
  46.     private int lineUp_current_Top, lineUp_current_Bottom;// 上线  
  47.   
  48.     private onTurnListener turnListener;  
  49.   
  50.     private ImageView imageHeader;  
  51.   
  52.     public void setImageHeader(ImageView imageHeader) {  
  53.         this.imageHeader = imageHeader;  
  54.     }  
  55.   
  56.     // 状态:上部,下部,默认  
  57.     private enum State {  
  58.         UP, DOWN, NOMAL  
  59.     };  
  60.   
  61.     // 默认状态  
  62.     private State state = State.NOMAL;  
  63.   
  64.     public void setTurnListener(onTurnListener turnListener) {  
  65.         this.turnListener = turnListener;  
  66.     }  
  67.   
  68.     public void setLine_up(View line_up) {  
  69.         this.line_up = line_up;  
  70.     }  
  71.   
  72.     // 注入背景图  
  73.     public void setImageView(ImageView imageView) {  
  74.         this.imageView = imageView;  
  75.     }  
  76.   
  77.     /*** 
  78.      * 构造方法 
  79.      *  
  80.      * @param context 
  81.      * @param attrs 
  82.      */  
  83.     public PersonalScrollView(Context context, AttributeSet attrs) {  
  84.         super(context, attrs);  
  85.     }  
  86.   
  87.     /*** 
  88.      * 根据 XML 生成视图工作完成.该函数在生成视图的最后调用,在所有子视图添加完之后. 即使子类覆盖了 onFinishInflate 
  89.      * 方法,也应该调用父类的方法,使该方法得以执行. 
  90.      */  
  91.     @Override  
  92.     protected void onFinishInflate() {  
  93.         if (getChildCount() > 0) {  
  94.             inner = getChildAt(0);  
  95.         }  
  96.     }  
  97.   
  98.     /** touch 事件处理 **/  
  99.     @Override  
  100.     public boolean onTouchEvent(MotionEvent ev) {  
  101.         if (inner != null) {  
  102.             commOnTouchEvent(ev);  
  103.         }  
  104.         // ture:禁止控件本身的滑动.  
  105.         if (shutTouch)  
  106.             return true;  
  107.         else  
  108.             return super.onTouchEvent(ev);  
  109.   
  110.     }  
  111.   
  112.     /*** 
  113.      * 触摸事件 
  114.      *  
  115.      * @param ev 
  116.      */  
  117.     public void commOnTouchEvent(MotionEvent ev) {  
  118.         int action = ev.getAction();  
  119.         switch (action) {  
  120.         case MotionEvent.ACTION_DOWN:  
  121.             initTouchY = ev.getY();  
  122.             current_Top = initTop = imageView.getTop();  
  123.             current_Bottom = initBottom = imageView.getBottom();  
  124.             if (line_up_top == 0) {  
  125.                 lineUp_current_Top = line_up_top = line_up.getTop();  
  126.                 lineUp_current_Bottom = line_up_bottom = line_up.getBottom();  
  127.             }  
  128.             break;  
  129.         case MotionEvent.ACTION_UP:  
  130.             /** 回缩动画 **/  
  131.             if (isNeedAnimation()) {  
  132.                 animation();  
  133.             }  
  134.   
  135.             if (getScrollY() == 0) {  
  136.                 state = State.NOMAL;  
  137.             }  
  138.   
  139.             isMoveing = false;  
  140.             touchY = 0;  
  141.             shutTouch = false;  
  142.             break;  
  143.   
  144.         /*** 
  145.          * 排除出第一次移动计算,因为第一次无法得知deltaY的高度, 然而我们也要进行初始化,就是第一次移动的时候让滑动距离归0. 
  146.          * 之后记录准确了就正常执行. 
  147.          */  
  148.         case MotionEvent.ACTION_MOVE:  
  149.   
  150.             touchY = ev.getY();  
  151.             deltaY = touchY - initTouchY;// 滑动距离  
  152.   
  153.             /** 对于首次Touch操作要判断方位:UP OR DOWN **/  
  154.             if (deltaY < 0 && state == state.NOMAL) {  
  155.                 state = State.UP;  
  156.             } else if (deltaY > 0 && state == state.NOMAL) {  
  157.                 state = State.DOWN;  
  158.             }  
  159.   
  160.             if (state == State.UP) {  
  161.                 deltaY = deltaY < 0 ? deltaY : 0;  
  162.                 isMoveing = false;  
  163.                 shutTouch = false;  
  164.   
  165.                 /** line_up **/  
  166.                 lineUp_current_Top = (int) (line_up_top - getScrollY());  
  167.                 lineUp_current_Bottom = (int) (line_up_bottom - getScrollY());  
  168.   
  169.                 Log.e(TAG, "top=" + getScrollY());  
  170.   
  171.                 line_up.layout(line_up.getLeft(), lineUp_current_Top,  
  172.                         line_up.getRight(), lineUp_current_Bottom);  
  173.   
  174.             } else if (state == state.DOWN) {  
  175.                 if (getScrollY() <= deltaY) {  
  176.                     shutTouch = true;  
  177.                     isMoveing = true;  
  178.                 }  
  179.                 deltaY = deltaY < 0 ? 0 : deltaY;  
  180.             }  
  181.   
  182.             if (isMoveing) {  
  183.                 // 初始化头部矩形  
  184.                 if (normal.isEmpty()) {  
  185.                     // 保存正常的布局位置  
  186.                     normal.set(inner.getLeft(), inner.getTop(),  
  187.                             inner.getRight(), inner.getBottom());  
  188.                 }  
  189.                 // 移动布局(手势移动的1/3)  
  190.                 float inner_move_H = deltaY / 5;  
  191.   
  192.                 inner.layout(normal.left, (int) (normal.top + inner_move_H),  
  193.                         normal.right, (int) (normal.bottom + inner_move_H));  
  194.   
  195.                 /** image_bg **/  
  196.                 float image_move_H = deltaY / 10;  
  197.                 current_Top = (int) (initTop + image_move_H);  
  198.                 current_Bottom = (int) (initBottom + image_move_H);  
  199.                 imageView.layout(imageView.getLeft(), current_Top,  
  200.                         imageView.getRight(), current_Bottom);  
  201.   
  202.                 /** line_up **/  
  203.                 lineUp_current_Top = (int) (line_up_top + inner_move_H);  
  204.                 lineUp_current_Bottom = (int) (line_up_bottom + inner_move_H);  
  205.                 line_up.layout(line_up.getLeft(), lineUp_current_Top,  
  206.                         line_up.getRight(), lineUp_current_Bottom);  
  207.             }  
  208.             break;  
  209.   
  210.         default:  
  211.             break;  
  212.   
  213.         }  
  214.     }  
  215.   
  216.     /*** 
  217.      * 回缩动画 
  218.      */  
  219.     public void animation() {  
  220.   
  221.         TranslateAnimation image_Anim = new TranslateAnimation(00,  
  222.                 Math.abs(initTop - current_Top), 0);  
  223.         image_Anim.setDuration(200);  
  224.         imageView.startAnimation(image_Anim);  
  225.   
  226.         imageView.layout(imageView.getLeft(), (int) initTop,  
  227.                 imageView.getRight(), (int) initBottom);  
  228.   
  229.         // 开启移动动画  
  230.         TranslateAnimation inner_Anim = new TranslateAnimation(00,  
  231.                 inner.getTop(), normal.top);  
  232.         inner_Anim.setDuration(200);  
  233.         inner.startAnimation(inner_Anim);  
  234.         inner.layout(normal.left, normal.top, normal.right, normal.bottom);  
  235.   
  236.         /** line_up **/  
  237.         TranslateAnimation line_up_Anim = new TranslateAnimation(00,  
  238.                 Math.abs(line_up_top - lineUp_current_Top), 0);  
  239.         line_up_Anim.setDuration(200);  
  240.         line_up.startAnimation(line_up_Anim);  
  241.         line_up.layout(line_up.getLeft(), line_up_top, line_up.getRight(),  
  242.                 line_up_bottom);  
  243.   
  244.         normal.setEmpty();  
  245.   
  246.         /** 动画执行 **/  
  247.         if (current_Top > initTop + 50 && turnListener != null)  
  248.             turnListener.onTurn();  
  249.   
  250.     }  
  251.   
  252.     /** 是否需要开启动画 **/  
  253.     public boolean isNeedAnimation() {  
  254.         return !normal.isEmpty();  
  255.     }  
  256.   
  257.     /*** 
  258.      * 执行翻转 
  259.      *  
  260.      * @author jia 
  261.      *  
  262.      */  
  263.     public interface onTurnListener {  
  264.   
  265.         /** 必须达到一定程度才执行 **/  
  266.         void onTurn();  
  267.     }  
  268.   
  269. }  


效果图:

                   

界面有点丑陋,不过UI可以自己根据需求进行调整.


最后我在多侃一点,这里我用的是TableLayout布局,不是ListView,因为ListView和ScrollView本身就有冲突,虽说有解决方案,但是我还是喜欢用TableLayout。代码里面模拟了3D旋转效果,这里就不解释了,网上相关文章也有好多。就说到这里,将源码供出,如果有问题请留言。


源码下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值