如何用RecyclerView實現(xiàn)貓眼電影選擇效果

一、簡介

在官方推出RecyclerView 控件之后,越來越多的人都使用它代替之前的ListView。除了最普通的列表顯示,RecyclerView還可以其他的很多效果,例如Banner等。在最近的一個電影票平臺項目中,使用RecyclerView實現(xiàn)了仿貓眼的電影選擇控件,如下圖所示:
在這里插入圖片描述

以上圖為例,我們的需求如下:

1、每一次滑動都讓圖片保持在中間。
2、第一張圖片的左邊距和最后一張的右邊距需要大于其他圖片的邊距使其保持在中間
3、點擊某張圖片時讓其滑動到中間
4、背景實現(xiàn)高斯模糊
5、在切換當(dāng)前電影時有一個背景淡入淡出的效果

二、實現(xiàn)思路

我們一步步實現(xiàn)我們的需求

(1)每一次滑動都讓圖片保持在正中間

滑動保持圖片在正中間,在RecyclerView24.2.0之后,Google官方給我們提供了一個SnapHelper的輔助類,可以幫助我們實現(xiàn)每次滑動結(jié)束都保持在居中位置:

val movieSnapHelper = LinearSnapHelper()
movieSnapHelper.attachToRecyclerView(movieRecyclerView)

LinearSnapHelper類是SnapHelper的一個子類,SnapHelper的另一個子類叫做PagerSnapHelper。顧名思義,兩者都可以是滑動結(jié)束時item保持在正中間,但是LinearSnapHelper可以一次滑動多個item,而PagerSnapHelper像ViewPager一樣限制你一次只能滑動一個item。

(2)第一張圖片的左邊距和最后一張的右邊距需要大于其他圖片的邊距使其保持在中間

由于第0個item和最后一個item的圖片邊距比較特殊,而其他的都是默認邊距,如果不做設(shè)置,第一張和最后一張圖片就無法位于正中間,如下圖所示:
在這里插入圖片描述
在這里插入圖片描述

如果想要是第0位置的圖片保持在中間,我們需要動態(tài)設(shè)置第0位置的圖片的左邊距為 (屏幕寬度-自定義ImageView圖片寬度-自定義ImageView的Margin)/2,例如我自定義的view參數(shù)為下圖
在這里插入圖片描述

圖片寬度+圖片margin為110dp,假設(shè)手機屏幕寬度為360dp,我們此時圖片的左邊距便設(shè)置為(360-110)/2 = 125 dp。

動態(tài)修改item的LayoutParams,我們不要在自定義的Adapter里直接更改,官方提供了ItemDecoration的api,可以給recyclerview的item添加裝飾,我們在這里自定義一個繼承RecyclerView.ItemDecoration的GalleryItemDecoration,然后重寫getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?)方法(此方法用于自定義item的偏移寬度),修改如下:

class GalleryItemDecoration : RecyclerView.ItemDecoration() {

    var mPageMargin = 10 //自定義默認item邊距
    var mLeftPageVisibleWidth = 125 //第一張圖片的左邊距

    override fun getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?) {
        val positon = parent?.getChildAdapterPosition(view) //獲得當(dāng)前item的position
        val itemCount = parent?.adapter?.itemCount //獲得item的數(shù)量
        val leftMargin = if (positon == 0) dpToPx(mLeftPageVisibleWidth) else dpToPx(mPageMargin) //如果position為0,設(shè)置leftMargin為計算后邊距,其他為默認邊距
        val rightMargin = if (positon == (itemCount!! - 1)) dpToPx(mLeftPageVisibleWidth) else dpToPx(mPageMargin) //同上,設(shè)置最后一張圖片
        val lp = view?.layoutParams as RecyclerView.LayoutParams
        lp.setMargins(leftMargin, 30, rightMargin, 60) //30和60分別是item到上下的margin
        view.layoutParams = lp //設(shè)置參數(shù)
        super.getItemOffsets(outRect, view, parent, state)
    }

    private fun dpToPx(dp: Int): Int { 
        return (dp * Resources.getSystem().displayMetrics.density + 0.5f).toInt() //dp轉(zhuǎn)px
    }
}

然后,recyclerview設(shè)置GalleryItemDecoration即可:

movieRecyclerview.addItemDecoration(GalleryItemDecoration())

(3)點擊某張圖片時讓其滑動到中間

在RecyclerView中,我們?nèi)绻枰瑒拥侥骋晃恢?,一般會使用RecyclerView.smoothScrollToPosition(idx)方法,但是在此處我們在設(shè)置item的點擊事件時,不能直接使用這個方法,因為這個方法只會將recyclerview滑動到idx位置的item可見便停止了,而無法移動到中間。

我們通過查詢,在stackoverflow上找到了實現(xiàn)思路,自定義一個LinearLayoutManager,代碼如下:

class CenterLayoutManager:LinearLayoutManager{
    constructor(context:Context):super(context)
    constructor(context:Context,orientation:Int,reverseLayout:Boolean):super(context,orientation,reverseLayout)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int):super(context, attrs, defStyleAttr, defStyleRes)

    override fun smoothScrollToPosition(recyclerView: RecyclerView?, state: RecyclerView.State?, position: Int) {
        val smoothScroller = CenterSmoothScroller(recyclerView!!.context)
        smoothScroller.targetPosition = position
        startSmoothScroll(smoothScroller)
    }

    private class CenterSmoothScroller internal constructor(context: Context) : LinearSmoothScroller(context) {
        override fun calculateDtToFit(viewStart: Int, viewEnd: Int, boxStart: Int, boxEnd: Int, snapPreference: Int): Int {
            return boxStart + (boxEnd - boxStart) / 2 - (viewStart + (viewEnd - viewStart) / 2)
        }

    }
}

我們通過查看源碼,RecyclerView.smoothScrollToPosition(idx)調(diào)用了LinearLayoutManager.smoothScrollToPosition方法,代碼中的calculateDtToFit 方法控制滑動的位置,其中參數(shù)中view為需要滑動可見的item,box為整個布局。 然后調(diào)用val movieLayoutManager = CenterLayoutManager(this)和 RecyclerView.smoothScrollToPosition(idx)便可以點擊滑動到中間。

(4)背景實現(xiàn)高斯模糊

高斯模糊有很多方法,推薦使用Native層的實現(xiàn),使用RenderScript,此處參考教程教你一分鐘實現(xiàn)動態(tài)模糊效果,自定義一個ImageUtil類進行處理:

class ImageUtils(val context: Context) {

    private var renderScript:RenderScript? = RenderScript.create(context)

    fun gaussianBlur(@IntRange(from = 1,to = 25)radius:Int,original:Bitmap):Bitmap{
        val input = Allocation.createFromBitmap(renderScript,original)
        val output = Allocation.createTyped(renderScript,input.type)
        val scriptInterinsicBlur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript))
        scriptInterinsicBlur.setRadius(radius.toFloat())
        scriptInterinsicBlur.setInput(input)
        scriptInterinsicBlur.forEach(output)
        output.copyTo(original)
        return original
    }
}

用法只需要new一個ImageUtils對象,傳入context,然后在方法里傳入模糊程度(1到25)和原始bitmap即可,然后將這個bitmap設(shè)置為RecyclerView的背景即可。

(5)在切換當(dāng)前電影時有一個背景淡入淡出的效果

private fun setMovieRecBg(idx: Int) {
        doAsync {
            val imageManager = ImageUtils(this@CinemaDetailActivity)
            val bgBitmap = Glide.with(applicationContext).asBitmap().load(mMovieList[idx].coverSrc).submit(300, 520).get()
            uiThread {
                if (!isActivityDestroyed(this@CinemaDetailActivity)) {
                    val curBg = BitmapDrawable(resources, imageManager.gaussianBlur(25, bgBitmap))
                    val preBg = if (bgCacheMap["PRE_BG"] == null) curBg else bgCacheMap["PRE_BG"]
                    val options = RequestOptions().placeholder(preBg).diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true)
                    Glide.with(this@CinemaDetailActivity).load(bgBitmap).apply(options).transition(DrawableTransitionOptions.withCrossFade(1000)).into(cinema_detail_moviebg)
                    bgCacheMap["PRE_BG"] = curBg
                }
            }
        }
    }

本例中使用Glide框架加載圖片,因為加載的是網(wǎng)絡(luò)url,在使用高斯模糊的時候我們需要使用方法將url轉(zhuǎn)為bitmap,因為是網(wǎng)絡(luò),我們不能再主線程里完成,因此需要新開一個線程,在Glide中,可以設(shè)定一個占位符,即網(wǎng)絡(luò)圖片加載之前的默認圖片,然后在加載圖片時可以使用transition進行淡入淡出,這里我們新建一個Map來緩存上一張圖片的背景圖片,然后當(dāng)做下一張圖片的占位符,便可以實現(xiàn)背景淡入淡出效果。
最后小編給大家整理的一些高級安卓程序員必備的學(xué)習(xí)資料
加QQ群即可獲取:4112676

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容