Android 自定義ListView滾動條樣式


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM