自定义ListView FastScroller滑块图片

image_thumb27.png

image_thumb28.png

设置快速滚动属性很容易,只需在布局的xml文件里设置属性即可:

  1. <listview android:id="@+id/listView" android:layout_width="fill_parent" 
  2.     android:layout_height="fill_parent" android:fastScrollEnabled="true" 
  3.     android:focusable="true" />
复制代码
但是有时候会发现设置属性无效,滚动ListView并未出现滑块。原因是该属性生效有最小记录限制。当ListView记录能够在4屏以内显示(也就是说滚动4页)就不会出现滑块。可能是api设计者认为这么少的记录不需要快速滚动。我的依据是android源代码,见FastScroller的常量声明:
  1. // Minimum number of pages to justify showing a fast scroll thumb 
  2.    private static int MIN_PAGES = 4;
复制代码
以及:
  1. // Are there enough pages to require fast scroll? Recompute only if total count changes 
  2.         if (mItemCount != totalItemCount && visibleItemCount > 0) {
  3.             mItemCount = totalItemCount; 
  4.             mLongList = mItemCount / visibleItemCount >= MIN_PAGES; 
  5. }
复制代码
通篇查看了ListView及其超累AbsListView,都未找到自定义图片的设置接口。看来是没打算让开发者更改了。但是用户要求我们自定义这个图片。那只能用非常手段了。经过分析发现,该图片是ListView超类AbsListView的一个成员mFastScroller对象的成员mThumbDrawable。这里mThumbDrawable是Drawable类型的。mFastScroller是FastScroller类型,这个类型比较麻烦,类的声明没有modifier,也就是default(package),只能供包内的类调用。因此反射代码写的稍微麻烦一些:
  1. try { 
  2.     Field f = AbsListView.class.getDeclaredField("mFastScroller"); 
  3.     f.setAccessible(true); 
  4.     Object o=f.get(listView); 
  5.     f=f.getType().getDeclaredField("mThumbDrawable"); 
  6.     f.setAccessible(true); 
  7.     Drawable drawable=(Drawable) f.get(o); 
  8.     drawable=getResources().getDrawable(R.drawable.icon); 
  9.     f.set(o,drawable); 
  10.     Toast.makeText(this, f.getType().getName(), 1000).show(); 
  11. } catch (Exception e) { 
  12.     throw new RuntimeException(e); 
  13. }
复制代码
这样就可以改变默认的滑块图片了。源代码见:    ListViewCustomerFastScroller-0.1.rar (49.15 KB, 下载次数: 775) 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值