閱讀538 返回首頁    go 阿裏雲 go 技術社區[雲棲]


使用Style自定義ListView快速滑動圖標

一、顯示ListView快速滑動塊圖標

       設想這樣一個場景,當ListView的內容有大於100頁的情況下,如果想滑動到第80頁,用手指滑動到指定位置,無疑是一件很費時的事情,如果想快速滑動到指定的位置,隻需加上ListView的fastScrollEnabled屬性等於true,啟用快速滑動功能即可。

<ListView
        android:
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fastScrollEnabled="true" />
注意:默認隻有當ListView的內容大於4頁時,才會顯示快速滑動塊。

讀者可能會問,我是怎麼知道要大於4頁時,ListView才會顯示快速滑動塊圖標。想知道原因,查一下ListView源碼中fastScrollEnabled這個屬性是怎麼被初始化的吧。咱們到Eclipse中按ctrl+shift+t打開ListView的源碼(前提是要和源碼關聯才能看到),你發現在ListView中並沒有fastScrollEnabled這個屬性,那就去父類AbsListView中找找吧,發現在AbsListView的構造方法中發現了初始化快速滑動塊的代碼(4.1.2源碼在788-789行):

boolean enableFastScroll = a.getBoolean(R.styleable.AbsListView_fastScrollEnabled, false);
setFastScrollEnabled(enableFastScroll);

下麵定位到setFastScrollEnabled方法:

/**
     * Enables fast scrolling by letting the user quickly scroll through lists by
     * dragging the fast scroll thumb. The adapter attached to the list may want
     * to implement {@link SectionIndexer} if it wishes to display alphabet preview and
     * jump between sections of the list.
     * @see SectionIndexer
     * @see #isFastScrollEnabled()
     * @param enabled whether or not to enable fast scrolling
     */
    public void setFastScrollEnabled(boolean enabled) {
        mFastScrollEnabled = enabled;
        if (enabled) {
            if (mFastScroller == null) {
                mFastScroller = new FastScroller(getContext(), this);
            }
        } else {
            if (mFastScroller != null) {
                mFastScroller.stop();
                mFastScroller = null;
            }
        }
    }
從setFastScrollEnabled方法得知,ListView的快速滑動塊是通過FastScroller這個類來創建的,接下來打開FastScroller的構造方法,來看下它創建滑動塊的流程。(FastScroller這個類在Eclipse關聯的源碼中看不到,要到Android Framework源碼中才能找到,Demo下載地址中包含了這個文件),下麵我們來看看FastScroller這個類的關鍵代碼:

package android.widget;

class FastScroller {
   
    //....省略部分源碼
      
    // Minimum number of pages to justify showing a fast scroll thumb
    private static int MIN_PAGES = 4;
    
    private static final int THUMB_DRAWABLE = 1;

    private static final int[] ATTRS = new int[] {
        android.R.attr.fastScrollTextColor,
        android.R.attr.fastScrollThumbDrawable,	// 定義快速滑動塊圖標的屬性
        android.R.attr.fastScrollTrackDrawable,
        android.R.attr.fastScrollPreviewBackgroundLeft,
        android.R.attr.fastScrollPreviewBackgroundRight,
        android.R.attr.fastScrollOverlayPosition
    };
    
    //....省略部分源碼
    
    private Drawable mThumbDrawable;// 快速滑動塊圖標

    public FastScroller(Context context, AbsListView listView) {
        mList = listView;
        init(context);
    }
    
    private void init(Context context) {
        // Get both the scrollbar states drawables
        TypedArray ta = context.getTheme().obtainStyledAttributes(ATTRS);
        useThumbDrawable(context, ta.getDrawable(THUMB_DRAWABLE));	// 獲取當前主題ListView的快速滑動塊圖標
        //....省略部分源碼
    }
    
    private void useThumbDrawable(Context context, Drawable drawable) {
        mThumbDrawable = drawable;
        if (drawable instanceof NinePatchDrawable) {
            mThumbW = context.getResources().getDimensionPixelSize(
                    com.android.internal.R.dimen.fastscroll_thumb_width);
            mThumbH = context.getResources().getDimensionPixelSize(
                    com.android.internal.R.dimen.fastscroll_thumb_height);
        } else {
            mThumbW = drawable.getIntrinsicWidth();
            mThumbH = drawable.getIntrinsicHeight();
        }
        mChangedBounds = true;
    }
    
    void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, 
            int totalItemCount) {
        // 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;    // 至少4頁才顯示滑動塊
        }
        
        if (mAlwaysShow) {	// android:fastScrollAlwaysVisible="true"
            mLongList = true;
        }
        
         //....省略部分源碼
    }
    
   //....省略部分源碼
}

由上述代碼得知,快速滑動塊圖標是由fastScrollThumbDrawable定義的,第8行定義了顯示快速滑動塊的最少頁數,第51行onScroll方法負責處理顯示快速滑動塊的邏輯。


二、自定義快速滑動塊圖標


        在eoe上看到有個貼子通過反射,動態修改FastScroller對象的mThumbDrawable屬性來改變快速滑動塊的圖標,這也不為於一種實現方式,但反射的效率較低。下麵將介紹使用Style的方式來自定義圖標。

        從FastScroller類的init方法中可以得知,mThumbDrawable是通過獲取當前Activity主題的android.R.attr.fastScrollThumbDrawable屬性賦值,既然是這樣的話,我們完全可以自定義一個主題,覆蓋android.R.attr.fastScrollThumbDrawable屬性對應的Drawable不就搞定了!

1、定義一個主題

<style name="ListViewFastScrollThumb" parent="@android:style/Theme.Light.NoTitleBar.Fullscreen">
     <item name="android:fastScrollThumbDrawable">@drawable/ic_launcher</item>
</style>
2、當前ListView所在Activity應用自定義的主題

<activity
    android:name="com.example.actionbardemo.MainActivity"
    android:label="@string/app_name"
    android:theme="@style/ListViewFastScrollThumb" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

3、驗證

public class MainActivity extends ListActivity {

	private static final int[] ATTRS = new int[] {
        android.R.attr.fastScrollThumbDrawable,
    };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Cheeses.sCheeseStrings));
		ImageView imageView = (ImageView) findViewById(R.id.fastScrollDrawable);
		
		Theme theme = getTheme();
		TypedArray a = theme.obtainStyledAttributes(ATTRS);
		Drawable drawable = a.getDrawable(0);
		imageView.setBackgroundDrawable(drawable);
	}
}
布局:

<LinearLayout xmlns:andro
    xmlns:tools="https://schemas.android.com/tools"
    android:
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ListView
        android:
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fastScrollEnabled="true" 
        />

</LinearLayout>

4、 原生的和自定義的快速滑動塊效果圖對比:

      

Demo下載地址:https://download.csdn.net/detail/xyang81/6788411


最後更新:2017-04-03 12:54:02

  上一篇:go C#——運算符重載和索引器
  下一篇:go java中List按照指定字段排序工具類