為了實現(xiàn)循序漸進的學(xué)習(xí),本節(jié)先來利用TabLayout,ViewPager2 ,RecyclerView實現(xiàn)實現(xiàn)歌單廣場頁面。網(wǎng)易云音樂APP的頁面效果如下所示:
首先我們利用TabLayout和ViewPager2來實現(xiàn)上下聯(lián)動的框架,讓上面部分Tab和下面部分左右滑動能關(guān)聯(lián)起來。
ViewPager2
ViewPager2是2019年Google開發(fā)大會發(fā)布的。然后現(xiàn)在已經(jīng)發(fā)布了穩(wěn)定版本1.0.0。
ViewPager2是基于RecyclerView進行的優(yōu)化,并且提供了如下一些新的功能:
- 支持 橫向horizontal 和 縱向vertical 的滾動
- 支持從右向左RTL的布局
- 支持動態(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元素
- 創(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
}
}
}
代碼很好理解:
- 在伴生對象中建立了有一個參數(shù)名key的getInstance類方法來創(chuàng)建PlayListFragment,
- 將參數(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])
}
}
代碼中兩個方法的作用是:
- 告訴ViewPager2總共顯示多少Fragment,即構(gòu)造函數(shù)中items的數(shù)組長度
- 告訴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
}
}
代碼的意義如下:
- 從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>
- 將字符串?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可以橫向滑動了。
提示:
設(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è)置的屬性
-
app:tabRippleColor="#F5F5F5"
是點擊TabItem時候的波紋顏色 -
app:tabIndicatorFullWidth="false"
Indicator的寬度和標(biāo)題長度一致,不是和TabItem的長度一致 -
app:tabMode="scrollable"
TabItem很多的情況下可以滾動 -
app:tabTextColor="#424242"
沒有選中的文字的顏色 -
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)起來。
效果如下
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è)置如下:
創(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)
}
}
}
這段代碼代表的意義如下:
- 新建的PlaylistItemAdapter需要繼承自RecyclerView.Adapter,且需要指明一個泛型,這個泛型類型是RecyclerView.ViewHolder的子類。
-
PlaylistItemAdapter需要復(fù)寫三個方法,
onCreateViewHolder
方法的作用是根據(jù)Item的布局生成PlaylistItemHolder對象。 -
onBindViewHolder
方法主要是實現(xiàn)數(shù)據(jù)和視圖的綁定,當(dāng)然這個綁定是通過RecyclerView.ViewHolder的bindPlayItem
方法實現(xiàn)的。 -
getItemCount
方法是告知RecyclerView應(yīng)該顯示多少個Item,而這個值是構(gòu)造傳入的playlists參數(shù)確定的。 - PlaylistItemHolder是RecyclerView.ViewHolder的子類,有一個view參數(shù)的構(gòu)造函數(shù)。
- 數(shù)據(jù)和視圖的綁定的具體實現(xiàn)。
- 由于圖片是從網(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
}
代碼含義說明:
- 定義一個空的ArrayList,作為Adapter的數(shù)據(jù)源
- 根據(jù)ArrayList初始化Adapter
- 將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()
}
- 網(wǎng)絡(luò)請求是上節(jié)的主要內(nèi)容,不再贅述
- 將請求到的數(shù)據(jù)放入數(shù)據(jù)源playItemList中
-
adapter調(diào)用
notifyDataSetChanged
執(zhí)行刷新界面
優(yōu)化界面
將圖片設(shè)置成有5dp的圓角
設(shè)置圓角有多種實現(xiàn)方法,這里介紹兩種:
方法一:使用clipToOutline和ViewOutlineProvider
- 給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)
}
}
-
bindPlayItem時ImageView調(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)該還是比較清晰的:
- 定義catName保存?zhèn)魅氲?strong>QueryKey
- 獲取傳入的QueryKey
-
requestData
方法是根據(jù)不同的QueryKey執(zhí)行不同的請求
效果
下節(jié)預(yù)告
這個界面目前還有個問題,就是沒法滑到底部后實現(xiàn)加載更多數(shù)據(jù)的功能。
Google提供了一個這Paging庫來實現(xiàn)加載更多,但是需要LiveData的支持,所以后面會介紹LiveData及其相關(guān)的知識再來實現(xiàn)加載更多的功能。
敬請期待。