前言
- 仿IOS回弹效果
- 为了增强用户体验,自定义一个可回弹的ScrollView是一个不错的选择,而且这种效果还是很简单的

把原来的ScollView标签替换一下就好了
<?xml version="1.0" encoding="utf-8"?> <com.mycompany.myapp.MyScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="match_parent" android:layout_width="match_parent" android:fillViewport="true"> <LinearLayout android:layout_height="match_parent" android:layout_width="match_parent" android:gravity="center" android:background="#FFABE346" android:elevation="1dp"> <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="可回弹的Scollview"/> </LinearLayout> </com.mycompany.myapp.MyScrollView>
public class MyScrollView extends ScrollView
{
private View convertView;
private Rect originalRect=new Rect();
private int startY,offsetY;
public MyScrollView(Context context)
{
super(context);
}
public MyScrollView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
}
@Override
protected void onFinishInflate()
{
super.onFinishInflate();
//获取子视图
convertView = getChildAt(0);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
super.onLayout(changed, l, t, r, b);
//记录原来的位置
originalRect.set(l,t,r,b);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev)
{
switch (ev.getAction())
{
case MotionEvent.ACTION_DOWN:
{
//记录第一次的手指触摸位置
startY = (int) ev.getY();
}
break;
case MotionEvent.ACTION_MOVE:
{
//记录拖动时的手指触摸位置
offsetY = ((int) ev.getY()) - startY;
//让子视图跟随手指拖动
convertView.layout(originalRect.left,originalRect.top+(int)(offsetY*0.5f)
,originalRect.right,originalRect.bottom+(int)(offsetY*0.5f));
}
break;
case MotionEvent.ACTION_UP:
{
//回弹动画
TranslateAnimation offsetAnim=new TranslateAnimation(0,0,convertView.getTop(),originalRect.top);
offsetAnim.setDuration(200);
convertView.startAnimation(offsetAnim);
//让子视图回到原来的位置
convertView.layout(originalRect.left,originalRect.top,originalRect.right,originalRect.bottom);
}
}
return super.dispatchTouchEvent(ev);
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)