今天又在IOS上看到列表的"阻尼"效果,就是列表拉到表頭或者表尾時,還能夠繼續往上或往下拉,鬆開手後,整個列表會彈回去,來看效果圖:
整個實現重點在overScrollBy這個方法上,當你滾動listview時會觸發此事件,它會根據表頭或表尾的座標,及你所給的maxOverScrollY最大滾動縱座標值來計算listview的表頭或表尾的座標。
默認的ListView的overScrollBy方法中maxOverScrollY=0;因此你只能看到在表頭或表尾有一條帶顏色的線閃燈,聽說,這是爲了不IOS的專利....
下面來看實現方式:
activity_main.xml: java
<com.example.tt.BaseListView android:id="@+id/mylistview" android:layout_width="match_parent" android:layout_height="match_parent" > </com.example.tt.BaseListView>
MainActivity.java: android
public class MainActivity extends Activity { private BaseListView listview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); listview = (BaseListView) findViewById(R.id.mylistview); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, new String[] { "A", "A", "A", "A", "A", "A", "A", "A", "A"}); listview.setAdapter(adapter); } }這個是重點
public class BaseListView extends ListView { private static final int MAX_Y_OVERSCROLL_DISTANCE = 200; private Context mContext; private int mMaxYOverscrollDistance; public BaseListView(Context context) { super(context); mContext = context; initBounceListView(); } public BaseListView(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; initBounceListView(); } public BaseListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mContext = context; initBounceListView(); } private void initBounceListView() { final DisplayMetrics metrics = mContext.getResources().getDisplayMetrics(); final float density = metrics.density; mMaxYOverscrollDistance = (int) (density * MAX_Y_OVERSCROLL_DISTANCE); } @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, mMaxYOverscrollDistance, isTouchEvent); } }