要將Android Scroller與ListView結合使用,可以通過自定義ListView來實現滾動效果。以下是一個簡單的示例代碼:
public class CustomListView extends ListView {
private Scroller mScroller;
public CustomListView(Context context) {
super(context);
mScroller = new Scroller(context);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
if (!mScroller.isFinished()) {
mScroller.abortAnimation();
}
}
mScroller.computeScrollOffset();
return super.onTouchEvent(ev);
}
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
smoothScrollTo(0, mScroller.getCurrY());
invalidate();
}
}
public void smoothScrollTo(int destX, int destY) {
int scrollY = getScrollY();
int delta = destY - scrollY;
mScroller.startScroll(0, scrollY, 0, delta, 1000);
invalidate();
}
}
<com.example.CustomListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
CustomListView listView = findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, new String[]{"Item 1", "Item 2", "Item 3"});
listView.setAdapter(adapter);
listView.smoothScrollTo(0, 100); // 滾動到指定位置
通過以上步驟,就可以實現在ListView中使用Android Scroller來實現滾動效果。