歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Android 自定義ListView仿iOS“阻尼”效果

今天又在iOS上看到列表的”阻尼”效果,就是列表拉到表頭或者表尾時,還可以繼續往上或往下拉,松開手後,整個列表會彈回去,來看效果圖:

整個實現重點在overScrollBy這個方法上,當你滾動listview時會觸發此事件,它會根據表頭或表尾的坐標,及你所給的maxOverScrollY最大滾動縱坐標值來計算listview的表頭或表尾的坐標。
 
Android默認的ListView的overScrollBy方法中maxOverScrollY=0;所以你只能看到在表頭或表尾有一條帶顏色的線閃燈,據說,這是為了避免IOS的專利….

    下面來看實現方式:

activity_main.xml:

<com.example.tt.BaseListView
        android:id="@+id/mylistview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </com.example.tt.BaseListView>

MainActivity.java:

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);
 }

}

    這個是重點

BaseListView.java

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);
 }
 
}

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved