自從Google推出了RecyclerView作爲ListView功能更加強大的替代品之後,越來越多的APP開始使用這個控件。RecyclerView可以優化程序性能,並且由於功能上的高度解耦,可以無成本地在ListView、GridView以及瀑布流之間切換,但是也正因爲如此,原來在ListView中理所當然的東西在RecyclerView中要自己來實現,比如分隔線,比如OnItemClickListener等(不是特別理解爲什麼Listener還要我們自己實現,我的做法就是往Adapter裏扔回調)
說到分隔線,可以去實現RecyclerView.ItemDecoration來定製,在鴻洋大大的博客裏有非常詳細的講解,按照這個來做其實也不麻煩,而且一次編寫複用終生,但是我做的時候還是想偷懶,不想去寫那麼多代碼,所以想用背景圖片來實現分隔線效果。
我的RecyclerView中每個item的背景是這樣的,用了selector實現點擊前後的變色效果
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/list_item_bg_pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/list_item_bg_unpressed" android:state_pressed="false"/>
</selector>
其中@drawable/list_item_bg_pressed是這樣
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 第一層,露出個小邊當分隔線 -->
<item>
<shape android:shape="rectangle">
<solid android:color="@color/color_list_item_divider"/>
<padding android:bottom="@dimen/dimen_list_item_divider_height"/>
</shape>
</item>
<!-- 第二層,真正的背景色 -->
<item>
<shape android:shape="rectangle">
<solid android:color="@color/color_list_item_bg_pressed"/>
</shape>
</item>
</layer-list>
使用layer-list來實現效果:第一層使用分割線的顏色,並在底部padding一個窄邊,第二層使用正常背景顏色,這樣寫而不是直接用一張圖片代替的原因是:如果使用普通圖片作爲背景,當圖片被拉伸時分隔線會明顯變粗,效果非常不美觀(當然.9圖片沒有問題,想了想還是直接用代碼寫了),而用代碼就沒有這個問題。這種效果我還用來實現一些輸入框。
@drawable/list_item_bg_unpressed同理,就是把第二層的顏色換了一下。
那麼爲什麼不直接用一張圖片來代替呢?因爲有些情況下RecyclerView每個條目的高度並不是一樣的,這樣對於普通圖片會產生縱向拉伸的效果,使得分隔線變得非常可怕,而用代碼來實現的.9效果則不會有這個問題。