MainActivity如下:
package cc.testlistviewscollbar; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.os.Bundle; import android.widget.AbsListView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.app.Activity; import android.graphics.drawable.Drawable; /** * Demo描述: * 利用反射修改ListView的ScollBar图标 * * 注意事项: * 并不是说这么做就一定会有效果. * 只有当ListView要显示的数据足够多(比如四屏或更多)时才会起到作用. * * 参考资料: * 1 http://blog.csdn.net/java2009cgh/article/details/7301197 * 2 http://blog.csdn.net/lfdfhl/article/details/10311505 * Thank you very much * */ public class MainActivity extends Activity { private ListView mListView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); setFastScrollBarForListView(); } private void init(){ mListView=(ListView) findViewById(R.id.listview); List<HashMap<String, Object>> list=new ArrayList<HashMap<String,Object>>(); HashMap<String, Object> hashMap=null; for (int i = 0; i < 100; i++) { hashMap=new HashMap<String, Object>(); hashMap.put("name", "小明"+i); hashMap.put("phone", "135"+i); hashMap.put("amount","500"+i); list.add(hashMap); } SimpleAdapter adapter=new SimpleAdapter(this, list, R.layout.listviewitem, new String []{"name","phone","amount"}, new int[]{R.id.name,R.id.phone,R.id.amount}); mListView.setAdapter(adapter); } //修改ListView的FastScroller图标 private void setFastScrollBarForListView() { try { Field field = AbsListView.class.getDeclaredField("mFastScroller"); field.setAccessible(true); Object object = field.get(mListView); field = field.getType().getDeclaredField("mThumbDrawable"); field.setAccessible(true); Drawable drawable = (Drawable) field.get(object); drawable = getResources().getDrawable(R.drawable.ic_launcher); field.set(object, drawable); } catch (Exception e) { System.out.println("----> 异常信息:"+e.toString()); e.printStackTrace(); } } }
main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ListView android:id="@+id/listview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_centerInParent="true" android:fastScrollEnabled="true" android:focusable="true" /> </RelativeLayout>
listviewitem如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="50dip" android:gravity="center" android:orientation="horizontal" > <TextView android:id="@+id/name" android:layout_width="100dip" android:layout_height="wrap_content" /> <TextView android:id="@+id/phone" android:layout_width="150dip" android:layout_height="wrap_content" /> <TextView android:id="@+id/amount" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout>