JetPack知识点实战系列四:使用 TabLayout,ViewPager2 ,RecyclerView实现实现歌单广场页面

为了实现循序渐进的学习,本节先来利用TabLayout,ViewPager2 ,RecyclerView实现实现歌单广场页面。网易云音乐APP的页面效果如下所示:

网易云音乐歌单广场界面

首先我们利用TabLayout和ViewPager2来实现上下联动的框架,让上面部分Tab和下面部分左右滑动能关联起来。

上下结构

ViewPager2

ViewPager2是2019年Google开发大会发布的。然后现在已经发布了稳定版本1.0.0

ViewPager2是基于RecyclerView进行的优化,并且提供了如下一些新的功能:

  1. 支持 横向horizontal纵向vertical 的滚动
  2. 支持从右向左RTL的布局
  3. 支持动态添加Fragments 或者 Views
设置ViewPager2可以通过以下一些步骤:

添加ViewPager2

  • 在app.gradle文件中添加如下依赖
implementation 'androidx.viewpager2:viewpager2:1.0.0'
  • 创建PlayListSquareFragment,在对应的布局文件R.layout.fragment_play_list_square中将根布局改为ConstraintLayout,在根布局中加入一个ViewPager2元素
加入ViewPager2
  • 创建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. 在伴生对象中建立了有一个参数名key的getInstance类方法来创建PlayListFragment,
  2. 将参数名key对应的值设置在TextView上

ViewPager2设置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,即构造函数中items的数组长度
  2. 告诉ViewPager2每个Fragment对应的对象,每个Fragment对象需要显示一个文字,这个是通过构造函数的items获取到的。
  • ViewPager2设置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中读取字符串数组
<string-array name="play_list_names">
    <item>推荐</item>
    <item>官方</item>
    <item>精品</item>
    <item>综艺</item>
    <item>工作</item>
    <item>华语</item>
    <item>流行</item>
</string-array>
  1. 将字符串数组设置给Adapter,然后将Adapter设置给ViewPager2对象

监听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注册回调
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    ...
    viewpager.registerOnPageChangeCallback(viewPagerChangeCallback)
}
总结

目前为止,达到了阶段性胜利,ViewPager2可以横向滑动了。

ViewPager2

提示:

设置viewPager.orientation = ORIENTATION_VERTICAL 就能实现垂直翻页的效果

设置viewPager.layoutDirection = ViewPager2.LAYOUT_DIRECTION_RTL 就能实现从右到左的布局

TabLayout

TabLayout属于Google的Material Design库中的控件。它能和ViewPager2完美的衔接。

设置TabLayout可以通过以下一些步骤:

添加TabLayout

  • 在项目的app对应的buildle.gradle中导入库:
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.

我们来看一下设置的属性

  1. app:tabRippleColor="#F5F5F5" 是点击TabItem时候的波纹颜色
  2. app:tabIndicatorFullWidth="false" Indicator的宽度和标题长度一致,不是和TabItem的长度一致
  3. app:tabMode="scrollable" TabItem很多的情况下可以滚动
  4. app:tabTextColor="#424242" 没有选中的文字的颜色
  5. app:tabSelectedTextColor="@color/colorAccent" 选中后文字的颜色
  • TabLayoutViewPager2关联
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    ...
    TabLayoutMediator(tablayout, viewpager) { tab, position ->
        tab.text = playListNamesArray[position]
    }.attach()
}

借助TabLayoutMediatorattach方法即可将TabLayoutViewPager2关联起来。

效果如下
效果

RecyclerView

到此为止我们实现了不同类型歌单页面的切换,但是每个歌单的内容页还没有内容。接下来我们用RecyclerView来实现歌单列表。

添加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添加网格布局管理器

  • 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的布局是网格布局,构造函数的3代表每行显示3个 Item

  • RecyclerView的每个Item设置样式

新建一个item_playlist.xml布局文件,布局文件的样式设置如下:

item样式

创建RecyclerView.Adapter

ViewPager2一样,RecyclerView也是利用适配器模式构建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需要复写三个方法,onCreateViewHolder方法的作用是根据Item的布局生成PlaylistItemHolder对象。
  3. onBindViewHolder方法主要是实现数据和视图的绑定,当然这个绑定是通过RecyclerView.ViewHolderbindPlayItem方法实现的。
  4. getItemCount方法是告知RecyclerView应该显示多少个Item,而这个值是构造传入的playlists参数确定的。
  5. PlaylistItemHolderRecyclerView.ViewHolder的子类,有一个view参数的构造函数。
  6. 数据和视图的绑定的具体实现。
  7. 由于图片是从网络加载的,这里将图片网络请求和加载交给了Glide库去实现。

说明: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的数据源
  2. 根据ArrayList初始化Adapter
  3. Adapter赋值给RecyclerView

目前为止,RecyclerView设置完成了。

不过很遗憾,还无法显示内容,因为playItemList还是个空数组,还没有元素。

网络数据请求和数据填充

onViewCreated中添加如下代码,就实现了网络数据请求和数据填充。

myScope.launch {
    // 1
    val response = MusicApiService.create().getHotPlaylist(30, 0)
    // 2
    playItemList.addAll(response.playlists)
    // 3
    adapter.notifyDataSetChanged()
}
  1. 网络请求是上节的主要内容,不再赘述
  2. 将请求到的数据放入数据源playItemList
  3. adapter调用notifyDataSetChanged执行刷新界面
效果

优化界面

将图片设置成有5dp的圆角

设置圆角有多种实现方法,这里介绍两种:

方法一:使用clipToOutlineViewOutlineProvider
  • View扩展一个方法
/* View设置圆角 */
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())
            }
        }
    }
}

  • 这里涉及到一个DPPX的问题,所以调用了ContextEx的转换方法
fun Context.dp2px(dpValue: Float): Int {
    val scale = resources.displayMetrics.density
    return (dpValue * scale + 0.5f).toInt()
}
  • ImageView直接调用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调用loadRoundCornerImage方法
 view.play_iv.loadRoundCornerImage(view.context, item.coverImgUrl,5)

几个界面的请求地址不同

接下来我们来实现不同的页面的请求对应的数据。

// 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()
    }
}

这段代码的意思应该还是比较清晰的:

  1. 定义catName保存传入的QueryKey
  2. 获取传入的QueryKey
  3. requestData方法是根据不同的QueryKey执行不同的请求
效果
最后效果

下节预告

这个界面目前还有个问题,就是没法滑到底部后实现加载更多数据的功能。

Google提供了一个这Paging库来实现加载更多,但是需要LiveData的支持,所以后面会介绍LiveData及其相关的知识再来实现加载更多的功能。

敬请期待。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容