具有弹性效果的ListView如何实现
扫描二维码
随时随地手机看文章
Android默认的ListView在滚动到顶端或底端,没有很好的提示,下面通过源码来实现弹性效果。
ListView中有一个控制滑动到边缘的处理方法:
protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent)
其中参数maxOverScrollX---Numbers of piexls to overscroll by in either direction along the Y axis.默认为0,修改这个数值就可以实现滑动到顶端的弹性效果。
//为满足多分辨率的需求,通过屏幕的density来计算maxOverScrollY的具体 DisplayMetrics metrics = mContext.getResources().getDisplayMetrics(); float density = metrics.density; mMaxOverDistance = (int) (density * mMaxOverDistance);
完整的工程
FlexibleListView.java
package sunny.example.ahfourflexiblelistviewtest; import android.annotation.SuppressLint; import android.content.Context; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.widget.ListView; @SuppressLint("NewApi") public class FlexibleListView extends ListView { private static int mMaxOverDistance = 50;//将滑动距离改为50,默认为0,无弹性效果 private Context mContext; public FlexibleListView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.mContext = context; initView(); } public FlexibleListView(Context context, AttributeSet attrs) { super(context, attrs); this.mContext = context; initView(); } public FlexibleListView(Context context) { super(context); this.mContext = context; initView(); } private void initView() { //为满足多分辨率的需求,通过屏幕的density来计算maxOverScrollY的具体 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); } }
FlexibleListViewTest.java
package sunny.example.ahfourflexiblelistviewtest; //具有弹性的ListView import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; public class FlexibleListViewTest extends Activity { private FlexibleListView mFlexibleListView; private String[] data = new String[30]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.flexible); for (int i = 0; i < 30; i++) { data[i] = "" + i; } mFlexibleListView = (FlexibleListView) findViewById(R.id.flexible_listview); mFlexibleListView.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, data)); } }
flexible.xml