為了實(shí)現(xiàn)循序漸進(jìn)的學(xué)習(xí)徐紧,本節(jié)先來(lái)利用TabLayout,ViewPager2 炭懊,RecyclerView實(shí)現(xiàn)實(shí)現(xiàn)歌單廣場(chǎng)頁(yè)面并级。網(wǎng)易云音樂(lè)APP的頁(yè)面效果如下所示:
首先我們利用TabLayout和ViewPager2來(lái)實(shí)現(xiàn)上下聯(lián)動(dòng)的框架,讓上面部分Tab和下面部分左右滑動(dòng)能關(guān)聯(lián)起來(lái)凛虽。
ViewPager2
ViewPager2是2019年Google開(kāi)發(fā)大會(huì)發(fā)布的死遭。然后現(xiàn)在已經(jīng)發(fā)布了穩(wěn)定版本1.0.0。
ViewPager2是基于RecyclerView進(jìn)行的優(yōu)化凯旋,并且提供了如下一些新的功能:
- 支持 橫向horizontal 和 縱向vertical 的滾動(dòng)
- 支持從右向左RTL的布局
- 支持動(dòng)態(tài)添加Fragments 或者 Views呀潭。
設(shè)置ViewPager2可以通過(guò)以下一些步驟:
添加ViewPager2
- 在app.gradle文件中添加如下依賴(lài)
implementation 'androidx.viewpager2:viewpager2:1.0.0'
- 創(chuàng)建PlayListSquareFragment,在對(duì)應(yīng)的布局文件R.layout.fragment_play_list_square中將根布局改為ConstraintLayout至非,在根布局中加入一個(gè)ViewPager2元素
- 創(chuàng)建PlayListFragment钠署,這個(gè)Fragment是展示每個(gè)獨(dú)立的歌單列表的頁(yè)面。目前只放置一個(gè)文本荒椭。
然后修改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
}
}
}
代碼很好理解:
- 在伴生對(duì)象中建立了有一個(gè)參數(shù)名key的getInstance類(lèi)方法來(lái)創(chuàng)建PlayListFragment,
- 將參數(shù)名key對(duì)應(yīng)的值設(shè)置在TextView上
ViewPager2設(shè)置Adapter
- 給PlayListSquareFragment頁(yè)面中的viewpager建立一個(gè)Adapter類(lèi)---PlayListSquareAdapter類(lèi)谐鼎。修改該類(lèi)的代碼如下:
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])
}
}
代碼中兩個(gè)方法的作用是:
- 告訴ViewPager2總共顯示多少Fragment,即構(gòu)造函數(shù)中items的數(shù)組長(zhǎng)度
- 告訴ViewPager2每個(gè)Fragment對(duì)應(yīng)的對(duì)象趣惠,每個(gè)Fragment對(duì)象需要顯示一個(gè)文字狸棍,這個(gè)是通過(guò)構(gòu)造函數(shù)的items獲取到的。
- 給ViewPager2設(shè)置Adapter
在PlayListSquareFragment
類(lèi)中加入如下代碼
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
}
}
代碼的意義如下:
- 從strings.xml中讀取字符串?dāng)?shù)組
<string-array name="play_list_names">
<item>推薦</item>
<item>官方</item>
<item>精品</item>
<item>綜藝</item>
<item>工作</item>
<item>華語(yǔ)</item>
<item>流行</item>
</string-array>
- 將字符串?dāng)?shù)組設(shè)置給Adapter味悄,然后將Adapter設(shè)置給ViewPager2對(duì)象
監(jiān)聽(tīng)ViewPager2的滾動(dòng)
- 在PlayListSquareFragment類(lèi)中添加一個(gè)
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注冊(cè)回調(diào)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
...
viewpager.registerOnPageChangeCallback(viewPagerChangeCallback)
}
總結(jié)
目前為止草戈,達(dá)到了階段性勝利,ViewPager2可以橫向滑動(dòng)了侍瑟。
提示:
設(shè)置viewPager.orientation = ORIENTATION_VERTICAL 就能實(shí)現(xiàn)垂直翻頁(yè)的效果
設(shè)置viewPager.layoutDirection = ViewPager2.LAYOUT_DIRECTION_RTL 就能實(shí)現(xiàn)從右到左的布局
TabLayout
TabLayout屬于Google的Material Design庫(kù)中的控件唐片。它能和ViewPager2完美的銜接。
設(shè)置TabLayout可以通過(guò)以下一些步驟:
添加TabLayout
- 在項(xiàng)目的app對(duì)應(yīng)的buildle.gradle中導(dǎo)入庫(kù):
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
, 因?yàn)檫€有一個(gè)TabLayout
.
我們來(lái)看一下設(shè)置的屬性
-
app:tabRippleColor="#F5F5F5"
是點(diǎn)擊TabItem時(shí)候的波紋顏色 -
app:tabIndicatorFullWidth="false"
Indicator的寬度和標(biāo)題長(zhǎng)度一致涨颜,不是和TabItem的長(zhǎng)度一致 -
app:tabMode="scrollable"
TabItem很多的情況下可以滾動(dòng) -
app:tabTextColor="#424242"
沒(méi)有選中的文字的顏色 -
app:tabSelectedTextColor="@color/colorAccent"
選中后文字的顏色
- 將TabLayout和ViewPager2關(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()
}
借助TabLayoutMediator的attach
方法即可將TabLayout和ViewPager2關(guān)聯(lián)起來(lái)费韭。
效果如下
RecyclerView
到此為止我們實(shí)現(xiàn)了不同類(lèi)型歌單頁(yè)面的切換,但是每個(gè)歌單的內(nèi)容頁(yè)還沒(méi)有內(nèi)容庭瑰。接下來(lái)我們用RecyclerView來(lái)實(shí)現(xiàn)歌單列表星持。
添加RecyclerView
- 修改fragment_play_list.xml,添加一個(gè)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 中初始化一個(gè)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個(gè) Item羹令。
- 給RecyclerView的每個(gè)Item設(shè)置樣式
新建一個(gè)item_playlist.xml布局文件,布局文件的樣式設(shè)置如下:
創(chuàng)建RecyclerView.Adapter
和ViewPager2一樣损痰,RecyclerView也是利用適配器模式構(gòu)建View福侈。需要新建一個(gè)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)
}
}
}
這段代碼代表的意義如下:
- 新建的PlaylistItemAdapter需要繼承自RecyclerView.Adapter卢未,且需要指明一個(gè)泛型肪凛,這個(gè)泛型類(lèi)型是RecyclerView.ViewHolder的子類(lèi)。
-
PlaylistItemAdapter需要復(fù)寫(xiě)三個(gè)方法辽社,
onCreateViewHolder
方法的作用是根據(jù)Item的布局生成PlaylistItemHolder對(duì)象伟墙。 -
onBindViewHolder
方法主要是實(shí)現(xiàn)數(shù)據(jù)和視圖的綁定,當(dāng)然這個(gè)綁定是通過(guò)RecyclerView.ViewHolder的bindPlayItem
方法實(shí)現(xiàn)的滴铅。 -
getItemCount
方法是告知RecyclerView應(yīng)該顯示多少個(gè)Item戳葵,而這個(gè)值是構(gòu)造傳入的playlists參數(shù)確定的。 - PlaylistItemHolder是RecyclerView.ViewHolder的子類(lèi)汉匙,有一個(gè)view參數(shù)的構(gòu)造函數(shù)拱烁。
- 數(shù)據(jù)和視圖的綁定的具體實(shí)現(xiàn)。
- 由于圖片是從網(wǎng)絡(luò)加載的噩翠,這里將圖片網(wǎng)絡(luò)請(qǐng)求和加載交給了Glide庫(kù)去實(shí)現(xiàn)戏自。
說(shuō)明:Glide庫(kù)需要引入依賴(lài)
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
將Adapter賦值給RecyclerView
回到PlayListFragment類(lèi),添加如下代碼:
// 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
}
代碼含義說(shuō)明:
- 定義一個(gè)空的ArrayList伤锚,作為Adapter的數(shù)據(jù)源
- 根據(jù)ArrayList初始化Adapter
- 將Adapter賦值給RecyclerView
目前為止擅笔,RecyclerView設(shè)置完成了。
不過(guò)很遺憾屯援,還無(wú)法顯示內(nèi)容猛们,因?yàn)?strong>playItemList還是個(gè)空數(shù)組,還沒(méi)有元素狞洋。
網(wǎng)絡(luò)數(shù)據(jù)請(qǐng)求和數(shù)據(jù)填充
在onViewCreated
中添加如下代碼弯淘,就實(shí)現(xiàn)了網(wǎng)絡(luò)數(shù)據(jù)請(qǐng)求和數(shù)據(jù)填充。
myScope.launch {
// 1
val response = MusicApiService.create().getHotPlaylist(30, 0)
// 2
playItemList.addAll(response.playlists)
// 3
adapter.notifyDataSetChanged()
}
- 網(wǎng)絡(luò)請(qǐng)求是上節(jié)的主要內(nèi)容徘铝,不再贅述
- 將請(qǐng)求到的數(shù)據(jù)放入數(shù)據(jù)源playItemList中
-
adapter調(diào)用
notifyDataSetChanged
執(zhí)行刷新界面
優(yōu)化界面
將圖片設(shè)置成有5dp的圓角
設(shè)置圓角有多種實(shí)現(xiàn)方法耳胎,這里介紹兩種:
方法一:使用clipToOutline和ViewOutlineProvider
- 給View擴(kuò)展一個(gè)方法
/* 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())
}
}
}
}
- 這里涉及到一個(gè)DP轉(zhuǎn)PX的問(wèn)題惯吕,所以調(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庫(kù)的RequestOptions
- 給ImageView擴(kuò)展一個(gè)方法
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)
}
}
-
bindPlayItem時(shí)ImageView調(diào)用
loadRoundCornerImage
方法
view.play_iv.loadRoundCornerImage(view.context, item.coverImgUrl,5)
幾個(gè)界面的請(qǐng)求地址不同
接下來(lái)我們來(lái)實(shí)現(xiàn)不同的頁(yè)面的請(qǐng)求對(duì)應(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)該還是比較清晰的:
- 定義catName保存?zhèn)魅氲?strong>QueryKey
- 獲取傳入的QueryKey
-
requestData
方法是根據(jù)不同的QueryKey執(zhí)行不同的請(qǐng)求
效果
下節(jié)預(yù)告
這個(gè)界面目前還有個(gè)問(wèn)題,就是沒(méi)法滑到底部后實(shí)現(xiàn)加載更多數(shù)據(jù)的功能废登。
Google提供了一個(gè)這Paging庫(kù)來(lái)實(shí)現(xiàn)加載更多缔赠,但是需要LiveData的支持啸蜜,所以后面會(huì)介紹LiveData及其相關(guān)的知識(shí)再來(lái)實(shí)現(xiàn)加載更多的功能。
敬請(qǐng)期待匣吊。