首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android HorizontalScrollView 滑動到最後一項:自定義 HorizontalListView 完整實現

     編輯:程式設計綜合問答

需求:HorizontalScrollView 默認顯示首項,需初始化滾動到末尾展示後續選項。原文提供完整 HorizontalListView 源碼(繼承 AdapterView<ListAdapter>),支持數據適配器、滑動回收、手勢衝突處理。

核心滾動方法

public synchronized void scrollTo(int x) {
    mScroller.startScroll(mNextX, 0, x - mNextX, 0);
    requestLayout();
}
// 調用:horizontalListView.scrollTo(maxX); // maxX 為內容總寬 - 視口寬

關鍵技術點

  • 視圖回收:mRemovedViewQueue 復用離屏 View,避免頻繁 GC
  • 手勢分發:onInterceptTouchEvent、dispatchTouchEvent 配合 GestureDetector 處理水平滑動與嵌套 ViewPager 衝突
  • 動態佈局:onLayout 中根據 mCurrentX 計算子 View 位置,支持邊界彈性

輕量替代方案

若不需複雜適配器,直接用 HorizontalScrollView + LinearLayout 並在 onWindowFocusChanged 中調用:

hsv.post(() -> hsv.fullScroll(View.FOCUS_RIGHT));

RecyclerView 現代寫法

RecyclerView rv = findViewById(R.id.rv);
rv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
rv.scrollToPosition(adapter.getItemCount() - 1);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved