android默认的ScrollView、ListView在最顶端下拉或者最底端上拉的时候,都不会带有反弹效果,很生硬的让你不能继续拖动,不像iOS那样可以回弹,个人认为,iOS的交互还是略好一点,那么我们也来在Android下实现下这个功能,先看下效果图:
那么我们今天的目标是一句话实现,如何去做呢
我们还是先看下代码:
package com.xys.flexible;
import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.widget.ScrollView;
public class FlexibleScrollView extends ScrollView {
private Context mContext;
private static int mMaxOverDistance = 50;
public FlexibleScrollView(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.mContext = context;
initView();
}
public FlexibleScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
initView();
}
public FlexibleScrollView(Context context) {
super(context);
this.mContext = context;
initView();
}
private void initView() {
DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();
float density = metrics.density;
mMaxOverDistance = (int) (density * mMaxOverDistance);
}
@Override
protected boolean overScrollBy(int deltaX, int deltaY, int scrollX,
int scrollY, int scrollRangeX, int scrollRangeY,
int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) {
return super.overScrollBy(deltaX, deltaY, scrollX, scrollY,
scrollRangeX, scrollRangeY, maxOverScrollX, mMaxOverDistance,
isTouchEvent);
}
}
也就是将overScrollBy中的maxOverScrollY改成了我们自己写的值。
测试布局:
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<com.xys.flexible.FlexibleScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_world" >
<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n......我是字符串......\n" />
</com.xys.flexible.FlexibleScrollView>
</RelativeLayout>以上。
原文:http://blog.csdn.net/eclipsexys/article/details/39673357