玩过新浪微博,qq空间等手机客户端的童鞋,都应该清楚,在主界面向下滑动时,会有一个阻尼回弹效果,看起来挺不错,接下来我们就来实现一下这种效果,下拉后回弹刷新界面,先看效果图:

这个是编辑器里面的界面效果,不言自明:

运行效果:

正常界面下:

下拉:

下拉结束:

实现代码:

主要部分就是重写的ScrollView:

package com.byl.scollower;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.ScrollView;

/**
 * @author baiyuliang 白玉梁
 * @date 2014年5月14日
 * @description 具有阻尼效果的ScrollView
 *
 */
public class MyScrollView extends ScrollView {

	private View inner;// 子View

	private float y;// 点击时y坐标
	private float y1;// 点击时y坐标
	private float y2;// 抬起时y坐标

	private Rect normal = new Rect();// 矩形(这里只是个形式,只是用于判断是否需要动画.)

	private boolean isCount = false;// 是否开始计算

	private boolean isMoveing = false;// 是否开始移动.

	private ImageView imageView;

	private int initTop, initbottom;// 初始高度
	private int top, bottom;// 拖动时时高度。

	public void setImageView(ImageView imageView) {
		this.imageView = imageView;
	}

	public MyScrollView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	private OnHeaderRefreshListener mOnHeaderRefreshListener;

	/***
	 * 根据 XML 生成视图工作完成.该函数在生成视图的最后调用,在所有子视图添加完之后. 即使子类覆盖了 onFinishInflate
	 * 方法,也应该调用父类的方法,使该方法得以执行.
	 */
	@Override
	protected void onFinishInflate() {
		if (getChildCount() > 0) {
			inner = getChildAt(0);
		}
	}

	/** touch 事件处理 **/
	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		if (inner != null) {
			commOnTouchEvent(ev);
		}
		return super.onTouchEvent(ev);
	}

	/***
	 * 触摸事件
	 *
	 * @param ev
	 */
	public void commOnTouchEvent(MotionEvent ev) {
		int action = ev.getAction();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
		    y1 = ev.getY();
			top = initTop = imageView.getTop();
			bottom = initbottom = imageView.getBottom();
			break;

		case MotionEvent.ACTION_UP:
			y2 = ev.getY();
			//y2-y1>0表示下拉动作
			if (isMoveing&&(y2-y1>0)){
				 Log.e("jj", "下拉结束" );
				 mOnHeaderRefreshListener.onHeaderRefresh(this);
			}

			isMoveing = false;
			// 手指松开.
			if (isNeedAnimation()) {

				animation();

			}

			break;
		/***
		 * 排除出第一次移动计算,因为第一次无法得知y坐标, 在MotionEvent.ACTION_DOWN中获取不到,
		 * 因为此时是MyScrollView的touch事件传递到到了LIstView的孩子item上面.所以从第二次计算开始.
		 * 然而我们也要进行初始化,就是第一次移动的时候让滑动距离归0. 之后记录准确了就正常执行.
		 */
		case MotionEvent.ACTION_MOVE:

			final float preY = y;// 按下时的y坐标
			float nowY = ev.getY();// 时时y坐标
			int deltaY = (int) (nowY - preY);// 滑动距离
			if (!isCount) {
				deltaY = 0; // 在这里要归0.
			}

			if (deltaY < 0 && top <= initTop)
				return;

			// 当滚动到最上或者最下时就不会再滚动,这时移动布局
			isNeedMove();

			if (isMoveing) {
				// 初始化头部矩形
				if (normal.isEmpty()) {
					// 保存正常的布局位置
					normal.set(inner.getLeft(), inner.getTop(),inner.getRight(), inner.getBottom());
				}

				// 移动布局
				inner.layout(inner.getLeft(), inner.getTop() + deltaY / 3,inner.getRight(), inner.getBottom() + deltaY / 3);

				top += (deltaY / 6);
				bottom += (deltaY / 6);
				imageView.layout(imageView.getLeft(), top,imageView.getRight(), bottom);
			}

			isCount = true;
			y = nowY;
			break;

		default:
			break;

		}
	}

	/***
	 * 回缩动画
	 */
	public void animation() {

		TranslateAnimation taa = new TranslateAnimation(0, 0, top + 200,
				initTop + 200);
		taa.setDuration(200);
		imageView.startAnimation(taa);
		imageView.layout(imageView.getLeft(), initTop, imageView.getRight(),
				initbottom);

		// 开启移动动画
		TranslateAnimation ta = new TranslateAnimation(0, 0, inner.getTop(),
				normal.top);
		ta.setDuration(200);
		inner.startAnimation(ta);
		// 设置回到正常的布局位置
		inner.layout(normal.left, normal.top, normal.right, normal.bottom);
		normal.setEmpty();

		isCount = false;
		y = 0;// 手指松开要归0.

	}

	// 是否需要开启动画
	public boolean isNeedAnimation() {
		return !normal.isEmpty();
	}

	/***
	 * 是否需要移动布局 inner.getMeasuredHeight():获取的是控件的总高度
	 *
	 * getHeight():获取的是屏幕的高度
	 *
	 * @return
	 */
	public void isNeedMove() {
		int offset = inner.getMeasuredHeight() - getHeight();
		int scrollY = getScrollY();
		// 0是顶部,后面那个是底部
//		if (scrollY == 0 || scrollY == offset) {
//			isMoveing = true;
//		}
		if (scrollY == 0) {
			isMoveing = true;
		}
	}

	public interface OnHeaderRefreshListener {
		public void onHeaderRefresh(MyScrollView view);
	}

	public void setOnHeaderRefreshListener(OnHeaderRefreshListener headerRefreshListener) {
		mOnHeaderRefreshListener = headerRefreshListener;
	}

}

并在其中定义了一个接口OnHeaderRefreshListener,主Activity实现该接口,下拉完成时回调,执行刷新操作,接下来看MainActivity:

package com.byl.scollower;

import com.byl.scollower.MyScrollView.OnHeaderRefreshListener;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnHeaderRefreshListener{

	private ImageView mBackgroundImageView = null;
	private Button mLoginButton = null;
	private MyScrollView mScrollView = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mBackgroundImageView = (ImageView) findViewById(R.id.personal_background_image);
		mLoginButton = (Button) findViewById(R.id.personal_login_button);
		mLoginButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Toast.makeText(getApplicationContext(), "登录", 1).show();
			}
		});
		mScrollView = (MyScrollView) findViewById(R.id.personal_scrollView);
		mScrollView.setImageView(mBackgroundImageView);
		mScrollView.setOnHeaderRefreshListener(this);

	}

	@Override
	public void onHeaderRefresh(MyScrollView view) {
		Toast.makeText(getApplicationContext(), "刷新", 1).show();
	}

}

布局文件activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <ImageView
            android:id="@+id/personal_background_image"
            android:layout_width="match_parent"
            android:layout_height="320dp"
            android:layout_alignParentTop="true"
            android:layout_marginTop="-100dp"
            android:background="@drawable/bg" />

        <com.byl.scollower.MyScrollView
            android:id="@+id/personal_scrollView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="#00000000"
                android:orientation="vertical" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="150dp"
                    android:orientation="vertical" >

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_marginTop="20dp"
                        android:text="欢迎来到白玉梁的博客专栏"
                        android:textColor="#ffffff"
                        android:textSize="20sp" />

                    <Button
                        android:id="@+id/personal_login_button"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_marginTop="5dp"
                        android:gravity="center"
                        android:text="登录"
                        android:textStyle="bold" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@drawable/android_layout_bg"
                    android:orientation="vertical" >

                </LinearLayout>
            </LinearLayout>
        </com.byl.scollower.MyScrollView>
    </RelativeLayout>

</RelativeLayout>

转载请注明出处:http://blog.csdn.net/baiyuliang2013/article/details/25815407

源码地址:http://download.csdn.net/detail/baiyuliang2013/7346831

ScrollView的阻尼回弹效果实现(仿qq空间)的更多相关文章

  1. 阻尼回弹效果的ScrollView嵌套GridView

    以前写过一篇带阻尼回弹效果的ScrollView,但是有些小问题,于是又重新整理了一下,这篇文章一是一个带阻尼的Scrollview,再个就是Scrollview嵌套GridView实现,而GridV ...

  2. JS仿QQ空间鼠标停在长图片时候图片自动上下滚动效果

    JS仿QQ空间鼠标停在长图片时候图片自动上下滚动效果 今天是2014年第一篇博客是关于类似于我们的qq空间长图片展示效果,因为一张很长的图片不可能全部把他展示出来,所以外层用了一个容器给他一个高度,超 ...

  3. 仿QQ空间和微信朋友圈,高解耦高复用高灵活

    先看看效果: 用极少的代码实现了 动态详情 及 二级评论 的 数据获取与处理 和 UI显示与交互,并且高解耦.高复用.高灵活. 动态列表界面MomentListFragment支持 下拉刷新与上拉加载 ...

  4. 仿QQ空间动态界面分享

    先看看效果: 用极少的代码实现了 动态详情 及 二级评论 的 数据获取与处理 和 UI显示与交互,并且高解耦.高复用.高灵活. 动态列表界面MomentListFragment支持 下拉刷新与上拉加载 ...

  5. Fragment,仿QQ空间

    转载请注明出处:http://blog.csdn.net/yangyu20121224/article/details/9023451          在今天的这篇文章当中,我依然会以实战加理论结合 ...

  6. iOS传感器集锦、飞机大战、开发调试工具、强制更新、Swift仿QQ空间头部等源码

    iOS精选源码 飞机大作战 MUPhotoPreview -简单易用的图片浏览器 LLDebugTool是一款针对开发者和测试者的调试工具,它可以帮... 多个UIScrollView.UITable ...

  7. Html - 仿QQ空间右下角工具浮动块

    仿QQ空间右下角工具浮动块 <style type="text/css"> .cy-tp-area>.cy-tp-fixbtn>.cy-tp-text { ...

  8. android 自定义scrollview 仿QQ空间效果 下拉伸缩顶部图片,上拉回弹 上拉滚动顶部title 颜色渐变

    首先要知道  自定义scrollview 仿QQ效果 下拉伸缩放大顶部图片 的原理是监听ontouch事件,在MotionEvent.ACTION_MOVE事件时候,使用不同倍数的系数,重置布局位置[ ...

  9. 仿QQ空间根据位置弹出PopupWindow显示更多操作效果

    我们打开QQ空间的时候有个箭头按钮点击之后弹出PopupWindow会根据位置的变化显示在箭头的上方还是下方,比普通的PopupWindow弹在屏幕中间显示好看的多. 先看QQ空间效果图:       ...

随机推荐

  1. 机器学习技法:16 Finale

    Roadmap Feature Exploitation Techniques Error Optimization Techniques Overfitting Elimination Techni ...

  2. python2.7-巡风源码阅读

    推荐个脚本示例网站:https://www.programcreek.com/python/example/404/thread.start_new_thread,里面可以搜索函数在代码中的写法,只有 ...

  3. chall.tasteless.eu 中的注入题

    第一题好像就很难,看了payload,算是涨见识了,感觉有点为了猜而猜. 题目给我们的时候是这样的:http://chall.tasteless.eu/level1/index.php?dir=ASC ...

  4. Redis常用命令--SortedSet

    SortedSet是一个类似于Set的集合数据类型,里面的每个字符串元素都关联到一个score(整数或浮点数),并且总是通过score来进行排序着. 并且可以取得一定范围内的元素. 在Redis中大概 ...

  5. [HAOI 2006]受欢迎的牛

    Description 每一头牛的愿望就是变成一头最受欢迎的牛.现在有N头牛,给你M对整数(A,B),表示牛A认为牛B受欢迎. 这种关系是具有传递性的,如果A认为B受欢迎,B认为C受欢迎,那么牛A也认 ...

  6. 亲戚(relative)

    [题目背景] Y 家是世界上最大的家族,HJZ 是其中一员. 现在 Y 家人想要拍一张全家福,却发现这是一个十分复杂的问题. . . . . . [题目描述] Y 家一共有 n 人 其中每个人最多有一 ...

  7. LOJ #6041. 事情的相似度

    Description 人的一生不仅要靠自我奋斗,还要考虑到历史的行程. 历史的行程可以抽象成一个 01 串,作为一个年纪比较大的人,你希望从历史的行程中获得一些姿势. 你发现在历史的不同时刻,不断的 ...

  8. 【USACO17JAN】Promotion Counting晋升者计数 线段树+离散化

    题目描述 The cows have once again tried to form a startup company, failing to remember from past experie ...

  9. NOI2017游记

    Day -1: THUSC后,下定决心好好学习,不过由于自制力太弱,还是没有忍住浪了几次. 老师把NOI前的天分为了4种:考试日.交流日.讲课日.自习日. 考试日是我被郭神短神妖神任神常神尹神龙神游神 ...

  10. spring 自定义事件发布及监听(简单实例)

    前言: Spring的AppilcaitionContext能够发布事件和注册相对应的事件监听器,因此,它有一套完整的事件发布和监听机制. 流程分析: 在一个完整的事件体系中,除了事件和监听器以外,还 ...