listviewandroidexceptionlayoutscrollobject
使用ListView FastScroller,預設滑塊和自訂滑塊圖片的樣子如下兩圖:
設定快速滾動屬性很容易,只需在布局的xml檔案裡設定屬性即可:
<ListView android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fastScrollEnabled="true"
android:focusable="true" />
但是有時候會發現設定屬性無效,滾動ListView並未出現滑塊。原因是該屬性生效有最小記錄限制。當ListView記錄能夠在4屏以內顯示(也就是說滾動4頁)就不會出現滑塊。可能是api設計者認為這麼少的記錄不需要快速滾動。
依據是android原始碼,見FastScroller的常量聲明:
// Minimum number of pages to justify showing a fast scroll thumb
private static int MIN_PAGES = 4;
以及:
// Are there enough pages to require fast scroll? Recompute only if total count changes
if (mItemCount != totalItemCount && visibleItemCount > 0) {
mItemCount = totalItemCount;
mLongList = mItemCount / visibleItemCount >= MIN_PAGES;
}
通篇查看了ListView及其超累AbsListView,都未找到自訂圖片的設定介面。看來是沒打算讓開發人員更改了。但是使用者要求我們自訂這個圖片。那隻能用非常手段了。
經過分析發現,該圖片是ListView超類AbsListView的一個成員mFastScroller對象的成員mThumbDrawable。這裡mThumbDrawable是Drawable類型的。mFastScroller是FastScroller類型,這個類型比較麻煩,類的聲明沒有modifier,也就是default(package),只能供包內的類調用。
因此反射代碼寫的稍微麻煩一些:
try {
Field f = AbsListView.class.getDeclaredField("mFastScroller");
f.setAccessible(true);
Object o=f.get(listView);
f=f.getType().getDeclaredField("mThumbDrawable");
f.setAccessible(true);
Drawable drawable=(Drawable) f.get(o);
drawable=getResources().getDrawable(R.drawable.icon);
f.set(o,drawable);
Toast.makeText(this, f.getType().getName(), 1000).show();
} catch (Exception e) {
throw new RuntimeException(e);
}