JetPack知識點實戰(zhàn)系列四:使用 TabLayout,ViewPager2 ,RecyclerView實現(xiàn)實現(xiàn)歌單廣場頁面

為了實現(xiàn)循序漸進的學(xué)習(xí),本節(jié)先來利用TabLayout,ViewPager2 ,RecyclerView實現(xiàn)實現(xiàn)歌單廣場頁面。網(wǎng)易云音樂APP的頁面效果如下所示:

網(wǎng)易云音樂歌單廣場界面

首先我們利用TabLayout和ViewPager2來實現(xiàn)上下聯(lián)動的框架,讓上面部分Tab和下面部分左右滑動能關(guān)聯(lián)起來。

上下結(jié)構(gòu)

ViewPager2

ViewPager2是2019年Google開發(fā)大會發(fā)布的。然后現(xiàn)在已經(jīng)發(fā)布了穩(wěn)定版本1.0.0

ViewPager2是基于RecyclerView進行的優(yōu)化,并且提供了如下一些新的功能:

  1. 支持 橫向horizontal縱向vertical 的滾動
  2. 支持從右向左RTL的布局
  3. 支持動態(tài)添加Fragments 或者 Views。
設(shè)置ViewPager2可以通過以下一些步驟:

添加ViewPager2

  • 在app.gradle文件中添加如下依賴
implementation 'androidx.viewpager2:viewpager2:1.0.0'
  • 創(chuàng)建PlayListSquareFragment,在對應(yīng)的布局文件R.layout.fragment_play_list_square中將根布局改為ConstraintLayout,在根布局中加入一個ViewPager2元素
加入ViewPager2
  • 創(chuàng)建PlayListFragment,這個Fragment是展示每個獨立的歌單列表的頁面。目前只放置一個文本。
歌單列表

然后修改PlayListFragment.kt文件的代碼如下:


class PlayListFragment : Fragment() {

    // 1 
    companion object {
        const val QueryKey = "query_key"
        fun getInstance(key: String): PlayListFragment {
            val fragment = PlayListFragment()
            Bundle().also {
                it.putString(QueryKey, key)
                fragment.arguments = it
            }
            return fragment
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_play_list, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 2
        arguments?.getString(QueryKey)?.let {
            query_tv.text = it
        }
    }

}

代碼很好理解:

  1. 在伴生對象中建立了有一個參數(shù)名key的getInstance類方法來創(chuàng)建PlayListFragment,
  2. 將參數(shù)名key對應(yīng)的值設(shè)置在TextView上

ViewPager2設(shè)置Adapter

  • PlayListSquareFragment頁面中的viewpager建立一個Adapter類---PlayListSquareAdapter類。修改該類的代碼如下:
class PlayListSquareAdapter(fragment: Fragment, private val items: Array<String>): FragmentStateAdapter(fragment) {

    // 1. 
    override fun getItemCount(): Int {
        return items.size
    }

    // 2
    override fun createFragment(position: Int): Fragment {
        return PlayListFragment.getInstance(items[position])
    }

}

代碼中兩個方法的作用是:

  1. 告訴ViewPager2總共顯示多少Fragment,即構(gòu)造函數(shù)中items的數(shù)組長度
  2. 告訴ViewPager2每個Fragment對應(yīng)的對象,每個Fragment對象需要顯示一個文字,這個是通過構(gòu)造函數(shù)的items獲取到的。
  • ViewPager2設(shè)置Adapter

PlayListSquareFragment類中加入如下代碼

private lateinit var playListNamesArray: Array<String>

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    // 1 
    playListNamesArray =  resources.getStringArray(R.array.play_list_names)
    // 2
    PlayListSquareAdapter(this, playListNamesArray).also {
        viewpager.adapter = it
    }

}

代碼的意義如下:

  1. strings.xml中讀取字符串?dāng)?shù)組
<string-array name="play_list_names">
    <item>推薦</item>
    <item>官方</item>
    <item>精品</item>
    <item>綜藝</item>
    <item>工作</item>
    <item>華語</item>
    <item>流行</item>
</string-array>
  1. 將字符串?dāng)?shù)組設(shè)置給Adapter,然后將Adapter設(shè)置給ViewPager2對象

監(jiān)聽ViewPager2的滾動

  • PlayListSquareFragment類中添加一個OnPageChangeCallback屬性
private val viewPagerChangeCallback = object : ViewPager2.OnPageChangeCallback() {
    override fun onPageSelected(position: Int) {
        super.onPageSelected(position)
        Toast.makeText(requireActivity(), "選擇了${playListNamesArray[position]}", Toast.LENGTH_SHORT).show()
    }
}
  • ViewPager2注冊回調(diào)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    ...
    viewpager.registerOnPageChangeCallback(viewPagerChangeCallback)
}
總結(jié)

目前為止,達到了階段性勝利,ViewPager2可以橫向滑動了。

ViewPager2

提示:

設(shè)置viewPager.orientation = ORIENTATION_VERTICAL 就能實現(xiàn)垂直翻頁的效果

設(shè)置viewPager.layoutDirection = ViewPager2.LAYOUT_DIRECTION_RTL 就能實現(xiàn)從右到左的布局

TabLayout

TabLayout屬于Google的Material Design庫中的控件。它能和ViewPager2完美的銜接。

設(shè)置TabLayout可以通過以下一些步驟:

添加TabLayout

  • 在項目的app對應(yīng)的buildle.gradle中導(dǎo)入庫:
implementation 'com.google.android.material:material:1.2.1'
  • 在布局文件中中加入TabLayout
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraint_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Fragment.PlayListSquareFragment">
    <!-- TabLayout -->
    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:tabRippleColor="#F5F5F5"
        app:tabIndicatorFullWidth="false"
        app:tabMode="scrollable"
        app:tabTextColor="#424242"
        app:tabSelectedTextColor="@color/colorAccent"
        />
    <!-- ViewPager2 -->
    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewpager"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tablayout">

    </androidx.viewpager2.widget.ViewPager2>
</androidx.constraintlayout.widget.ConstraintLayout>

注意:引入的是com.google.android.material.tabs.TabLayout, 因為還有一個TabLayout.

我們來看一下設(shè)置的屬性

  1. app:tabRippleColor="#F5F5F5" 是點擊TabItem時候的波紋顏色
  2. app:tabIndicatorFullWidth="false" Indicator的寬度和標(biāo)題長度一致,不是和TabItem的長度一致
  3. app:tabMode="scrollable" TabItem很多的情況下可以滾動
  4. app:tabTextColor="#424242" 沒有選中的文字的顏色
  5. app:tabSelectedTextColor="@color/colorAccent" 選中后文字的顏色
  • TabLayoutViewPager2關(guān)聯(lián)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    ...
    TabLayoutMediator(tablayout, viewpager) { tab, position ->
        tab.text = playListNamesArray[position]
    }.attach()
}

借助TabLayoutMediatorattach方法即可將TabLayoutViewPager2關(guān)聯(lián)起來。

效果如下
效果

RecyclerView

到此為止我們實現(xiàn)了不同類型歌單頁面的切換,但是每個歌單的內(nèi)容頁還沒有內(nèi)容。接下來我們用RecyclerView來實現(xiàn)歌單列表。

添加RecyclerView

  • 修改fragment_play_list.xml,添加一個RecyclerView作為容器
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraint_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Fragment.PlayListFragment" >

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

給RecyclerView添加網(wǎng)格布局管理器

  • PlayListFragment 中初始化一個GridLayoutManager,然后賦值給RecyclerView
private lateinit var grideLayoutManager: GridLayoutManager

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    // 1.2
    grideLayoutManager = GridLayoutManager(requireActivity(), 3)
    recyclerview.layoutManager = grideLayoutManager
}

GridLayoutManager的布局是網(wǎng)格布局,構(gòu)造函數(shù)的3代表每行顯示3個 Item。

  • RecyclerView的每個Item設(shè)置樣式

新建一個item_playlist.xml布局文件,布局文件的樣式設(shè)置如下:

item樣式

創(chuàng)建RecyclerView.Adapter

ViewPager2一樣,RecyclerView也是利用適配器模式構(gòu)建View。需要新建一個Adapter繼承自RecyclerView.Adapter。

適配器的代碼如下:

// 1
class PlaylistItemAdapter(private val playlists: List<PlayItem>):
    RecyclerView.Adapter<PlaylistItemAdapter.PlaylistItemHolder>() {

    // 2
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): PlaylistItemHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.item_playlist, parent, false)
        return PlaylistItemHolder(v)
    }

    // 3
    override fun onBindViewHolder(holder: PlaylistItemHolder, position: Int) {
        val playitem = playlists[position]
        holder.bindPlayItem(playitem)
    }

    // 4
    override fun getItemCount() = playlists.size


    // 5
    class PlaylistItemHolder(private val view: View) : RecyclerView.ViewHolder(view) {
        
        private var playItem: PlayItem? = null

        // 6
        fun bindPlayItem(item: PlayItem) {
            playItem = item
            view.play_title_tv.text = item.name
            if (item.playCount > 100000) {
                view.number_tv.text = view.resources.getString(R.string.wan, item.playCount/ 10000)
            } else {
                view.number_tv.text = "${item.playCount}"
            }
            if (item.highQuality) {
                view.highquality_iv.visibility = View.VISIBLE
            } else {
                view.highquality_iv.visibility = View.INVISIBLE
            }
            // 7
            Glide.with(view.context).load(item.coverImgUrl).into(view.play_iv)
        }
    }

}

這段代碼代表的意義如下:

  1. 新建的PlaylistItemAdapter需要繼承自RecyclerView.Adapter,且需要指明一個泛型,這個泛型類型是RecyclerView.ViewHolder的子類。
  2. PlaylistItemAdapter需要復(fù)寫三個方法,onCreateViewHolder方法的作用是根據(jù)Item的布局生成PlaylistItemHolder對象。
  3. onBindViewHolder方法主要是實現(xiàn)數(shù)據(jù)和視圖的綁定,當(dāng)然這個綁定是通過RecyclerView.ViewHolderbindPlayItem方法實現(xiàn)的。
  4. getItemCount方法是告知RecyclerView應(yīng)該顯示多少個Item,而這個值是構(gòu)造傳入的playlists參數(shù)確定的。
  5. PlaylistItemHolderRecyclerView.ViewHolder的子類,有一個view參數(shù)的構(gòu)造函數(shù)。
  6. 數(shù)據(jù)和視圖的綁定的具體實現(xiàn)。
  7. 由于圖片是從網(wǎng)絡(luò)加載的,這里將圖片網(wǎng)絡(luò)請求和加載交給了Glide庫去實現(xiàn)。

說明:Glide庫需要引入依賴

implementation 'com.github.bumptech.glide:glide:4.11.0'

annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'

將Adapter賦值給RecyclerView

回到PlayListFragment類,添加如下代碼:

// 1
private var playItemList: ArrayList<PlayItem> = ArrayList()
// 
private lateinit var adapter: PlaylistItemAdapter

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    ...
    // 2
    adapter = PlaylistItemAdapter(playItemList)
    // 3
    recyclerview.adapter = adapter
}

代碼含義說明:

  1. 定義一個空的ArrayList,作為Adapter的數(shù)據(jù)源
  2. 根據(jù)ArrayList初始化Adapter
  3. Adapter賦值給RecyclerView

目前為止,RecyclerView設(shè)置完成了。

不過很遺憾,還無法顯示內(nèi)容,因為playItemList還是個空數(shù)組,還沒有元素。

網(wǎng)絡(luò)數(shù)據(jù)請求和數(shù)據(jù)填充

onViewCreated中添加如下代碼,就實現(xiàn)了網(wǎng)絡(luò)數(shù)據(jù)請求和數(shù)據(jù)填充。

myScope.launch {
    // 1
    val response = MusicApiService.create().getHotPlaylist(30, 0)
    // 2
    playItemList.addAll(response.playlists)
    // 3
    adapter.notifyDataSetChanged()
}
  1. 網(wǎng)絡(luò)請求是上節(jié)的主要內(nèi)容,不再贅述
  2. 將請求到的數(shù)據(jù)放入數(shù)據(jù)源playItemList
  3. adapter調(diào)用notifyDataSetChanged執(zhí)行刷新界面
效果

優(yōu)化界面

將圖片設(shè)置成有5dp的圓角

設(shè)置圓角有多種實現(xiàn)方法,這里介紹兩種:

方法一:使用clipToOutlineViewOutlineProvider
  • View擴展一個方法
/* View設(shè)置圓角 */
fun View.clipViewCornerByDp(dp: Float) {
    clipToOutline = true
    outlineProvider = object : ViewOutlineProvider() {
        override fun getOutline(view: View?, outline: Outline?) {
            view?.let {
                outline?.setRoundRect(0, 0, width, height, it.context.dp2px(dp).toFloat())
            }
        }
    }
}

  • 這里涉及到一個DP轉(zhuǎn)PX的問題,所以調(diào)用了ContextEx的轉(zhuǎn)換方法
fun Context.dp2px(dpValue: Float): Int {
    val scale = resources.displayMetrics.density
    return (dpValue * scale + 0.5f).toInt()
}
  • ImageView直接調(diào)用clipViewCornerByDp方法
override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): PlaylistItemHolder {
    val v = LayoutInflater.from(parent.context).inflate(R.layout.item_playlist, parent, false)
    // 使用的地方
    v.play_iv.clipViewCornerByDp(5.0F)
    return PlaylistItemHolder(v)
}
方法二:使用Glide庫的RequestOptions
  • 給ImageView擴展一個方法
fun ImageView.loadRoundCornerImage(context: Context, path: String, roundingRadius: Int = 5, placeholder: Int = R.mipmap.ic_launcher, useCache: Boolean = false) {
    getOptions(placeholder, useCache).also {
        Glide.with(context).load(path).apply(RequestOptions.bitmapTransform(RoundedCorners(context.dp2px(roundingRadius.toFloat())))).apply(it).into(this)
    }
}
  • bindPlayItemImageView調(diào)用loadRoundCornerImage方法
 view.play_iv.loadRoundCornerImage(view.context, item.coverImgUrl,5)

幾個界面的請求地址不同

接下來我們來實現(xiàn)不同的頁面的請求對應(yīng)的數(shù)據(jù)。

// 1
private lateinit var catName: String


override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    ...
    // 2
    arguments?.getString(QueryKey)?.let {
        catName = it
    }
    // 3
    requestData()
}


fun requestData() {
    myScope.launch {
        when (catName) {
            "推薦" -> {
                val response = MusicApiService.create().getRecommendPlaylist(30, 0)
                playItemList.addAll(response.playlists)
            }
            "精品" -> {
                val response = MusicApiService.create().getHighQualityPlaylist(30, 0)
                playItemList.addAll(response.playlists)
            }
            "官方" -> {
                val response = MusicApiService.create().getCatPlaylist(30, 0, "new", null)
                playItemList.addAll(response.playlists)
                }
            else -> {
                val response = MusicApiService.create().getCatPlaylist(30, 0, null, catName)
                playItemList.addAll(response.playlists)
            }
        }
        adapter.notifyDataSetChanged()
    }
}

這段代碼的意思應(yīng)該還是比較清晰的:

  1. 定義catName保存?zhèn)魅氲?strong>QueryKey
  2. 獲取傳入的QueryKey
  3. requestData方法是根據(jù)不同的QueryKey執(zhí)行不同的請求
效果
最后效果

下節(jié)預(yù)告

這個界面目前還有個問題,就是沒法滑到底部后實現(xiàn)加載更多數(shù)據(jù)的功能。

Google提供了一個這Paging庫來實現(xiàn)加載更多,但是需要LiveData的支持,所以后面會介紹LiveData及其相關(guān)的知識再來實現(xiàn)加載更多的功能。

敬請期待。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,488評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,034評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,327評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,554評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 71,337評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,883評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,975評論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,114評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,625評論 1 332
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,555評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,737評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,244評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 43,973評論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,362評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,615評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,343評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 47,699評論 2 370

推薦閱讀更多精彩內(nèi)容