当前位置:网站首页>RecyclerView的高效使用第一节
RecyclerView的高效使用第一节
2022-07-31 14:51:00 【[email protected]】
在开发的过程中列表相关的布局是最不可或缺的一部分,而掌握一些高效的技巧可以帮助我们提升开发效率的同时,还能优化代码,减少冗余和bug的产生。
1.listitem实时预览
在UI绘制时,免不了进行细节和样式的调整,如果每次的调整都去run之后查看效果,则效率低下,使用listitem,则可以避免运行,直接使用AndroidStudio自带的预览功能进行调试
例如
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rv_student" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" tools:listitem="@layout/item_study" tools:context=".one.StudentActivity" />
效果如下:
2,xml中设置layoutManager
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rv_student" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" tools:listitem="@layout/item_study" android:orientation="vertical" app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" tools:context=".one.StudentActivity" />
在布局代码中可以直接设置LayoutManager类型和相关的一些属性,例如方向,网格布局时每一行的个数等。
3,使用默认的分割线
可以使用官方提供的默认的分割线样式,减少重复的创建。
//添加默认的分割线
rv_student.addItemDecoration(DividerItemDecoration(this,
(rv_student.layoutManager as LinearLayoutManager).orientation))
如需个性化定制,需要自己基于ItemDecoration进行定制
4,添加Item点击事件
使用Kotlin函数式的思想,快捷的添加点击事件
1)在Adapter的构造函数中添加入参
class StudentAdapter(private val data:ArrayList<StudentInfo>,
private val itemClick:(StudentInfo) ->Unit):
RecyclerView.Adapter<StudentAdapter.ViewHolder>() {
}
2)初始化Adapter时传入点击的函数
//学生数据列表
private val studentEntities = ArrayList<StudentInfo>()
//适配器
private val studentAdapter by lazy {
StudentAdapter(studentEntities,this::onStudentItemClick)
}
/**
*点击事件
*/
private fun onStudentItemClick(entity:StudentInfo){
/**
* 点击Item时,获取的当前点击的用户信息
*/
Log.d(TAG,"onStudentItemClick()--->$entity")
Toast.makeText(this,"$entity",Toast.LENGTH_LONG).show()
}
3)使用时
itemView.setOnClickListener { itemClick(entity) }
5,Adapter中获取上下文
在onCreateViewHolder中获取context对象,减少构建时的传参
//定义上下文
private lateinit var context:Context
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
context = parent.context
}
如上功能完成的代码如下:
1,item布局
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="16dp" xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.appcompat.widget.AppCompatImageView android:id="@+id/iv_icon" android:layout_width="48dp" app:layout_constraintLeft_toLeftOf="parent" android:src="@mipmap/ic_launcher" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" android:layout_height="48dp"/>
<TextView app:layout_constraintTop_toTopOf="parent" app:layout_constraintLeft_toRightOf="@+id/iv_icon" android:layout_width="wrap_content" android:id="@+id/tv_title" android:gravity="center" android:text="Study" android:textSize="22sp" android:layout_marginLeft="16dp" app:layout_constraintVertical_chainStyle="packed" app:layout_constraintBottom_toTopOf="@+id/tv_second" android:textColor="@android:color/black" android:layout_height="wrap_content"/>
<TextView android:id="@+id/tv_subtitle" android:layout_width="wrap_content" app:layout_constraintLeft_toRightOf="@+id/iv_icon" app:layout_constraintTop_toBottomOf="@+id/tv_study" android:textSize="16sp" android:layout_marginLeft="16dp" app:layout_constraintVertical_chainStyle="packed" android:text="zhansan" android:textColor="@color/cardview_dark_background" app:layout_constraintBottom_toBottomOf="parent" android:layout_height="wrap_content"/>
<TextView android:id="@+id/tv_gender" android:layout_width="wrap_content" android:textSize="18sp" android:text="男" android:textColor="@color/material_on_surface_emphasis_high_type" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" android:layout_height="wrap_content"/>
</androidx.constraintlayout.widget.ConstraintLayout>
2,Activity布局
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rv_student" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" tools:listitem="@layout/item_study" android:orientation="vertical" app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" tools:context=".one.StudentActivity" />
3,Activity代码
package com.example.recyclerviewstudy.one
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.recyclerviewstudy.R
import com.example.recyclerviewstudy.StudentInfo
class StudentActivity : AppCompatActivity() {
companion object{
val TAG = this::class.simpleName
}
//学生数据列表
private val studentEntities = ArrayList<StudentInfo>()
//适配器
private val studentAdapter by lazy {
StudentAdapter(studentEntities,this::onStudentItemClick)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_study)
initRecyclerView()
}
private fun initRecyclerView(){
val rv_student = findViewById<RecyclerView>(R.id.rv_student)
//添加默认的分割线
rv_student.addItemDecoration(DividerItemDecoration(this,
(rv_student.layoutManager as LinearLayoutManager).orientation))
rv_student.adapter = studentAdapter
produceData()
}
private fun onStudentItemClick(entity:StudentInfo){
/**
* 点击Item时,获取的当前点击的用户信息
*/
Log.d(TAG,"onStudentItemClick()--->$entity")
Toast.makeText(this,"$entity",Toast.LENGTH_LONG).show()
}
//生产数据
private fun produceData(){
for (i in 0..20){
studentEntities.add(StudentInfo("zhang san $i",i,if (i%2==0)"男" else "女"))
}
}
}
4,Adapter完整代码
package com.example.recyclerviewstudy.one
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.recyclerviewstudy.R
import com.example.recyclerviewstudy.StudentInfo
class StudentAdapter(private val data:ArrayList<StudentInfo>,
private val itemClick:(StudentInfo) ->Unit):
RecyclerView.Adapter<StudentAdapter.ViewHolder>() {
//定义上下文
private lateinit var context:Context
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
context = parent.context
return ViewHolder(LayoutInflater.from(context)
.inflate(R.layout.item_study,parent,false),itemClick)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(data[position])
}
override fun getItemCount() = data.size
inner class ViewHolder(itemView:View,val itemClick:(StudentInfo) -> Unit):RecyclerView.ViewHolder(itemView){
val tv_name:TextView = itemView.findViewById(R.id.tv_title)
val tv_age:TextView = itemView.findViewById(R.id.tv_subtitle)
val tv_gender:TextView = itemView.findViewById(R.id.tv_gender)
private lateinit var entity:StudentInfo
init {
itemView.setOnClickListener { itemClick(entity) }
}
fun bind(entity:StudentInfo){
this.entity = entity
entity.apply {
tv_name.text = name
tv_age.text = "$age"
tv_gender.text = gander
}
}
}
}
针对RecyclerView相关的实际使用目前学到的就这些,具体实践还需结合自己项目架构进行优化实现。
RecyclerView是开发中必不可少的,虽然它的功能和性能相较于ListView有了很大的改善和提升,但使用不当还是会存在一些性能问题,且目还有进一步的优化空间,结合mCacheViewExtension和DiffUtil的实现,让你的UI更加流畅。
版权声明
本文为[[email protected]]所创,转载请带上原文链接,感谢
https://blog.csdn.net/zdc9023/article/details/125998038
边栏推荐
- charles进行弱网测试(app弱网测试怎么做)
- The JVM a class loader
- Getting started with UnityShader (1) - GPU and Shader
- 网线RJ45接口针脚[通俗易懂]
- SetoolKit User Guide
- [QNX Hypervisor 2.2 User Manual] 9.13 rom
- Message queue data storage MySQL table design
- Small test knife: Go reflection helped me convert Excel to Struct
- Five dimensions to start MySQL optimization
- 【Pytorch】torch.argmax()用法
猜你喜欢

The paper manual becomes 3D animation in seconds, the latest research of Wu Jiajun of Stanford University, selected for ECCV 2022

QGIS 加载WMS数据,重新投影

名创优品斥资6.95亿购买创始人叶国富所持办公楼股权

The recently popular domestic interface artifact Apipost experience

Small test knife: Go reflection helped me convert Excel to Struct

Asynchronous processing business using CompletableFuture

I summed up the bad MySQL interview questions

The JVM a class loader

Nuget package and upload tutorial

"Listen to me, thank you" can be said in ancient poetry?Tsinghua University has developed an artifact of "Searching Sentences According to Meaning", which can search for the famous sayings you want wi
随机推荐
redhat/openssl generates a self-signed ca certificate and uses it
MySQL【子查询】
小试牛刀:Go 反射帮我把 Excel 转成 Struct
Sentinel安装与部署
MySQL 23道经典面试吊打面试官
OAuth2:微服务权限校验Session共享
BigDecimal 简介,常用方法
看交互设计如何集成到Scrum敏捷流程中
Detailed guide to compare two tables using natural full join in SQL
深入浅出边缘云 | 4. 生命周期管理
力扣:738.单调递增的数字
Why do we need to sub-library and sub-table?
四象限时间管理有多好用?
Essential Learning for Getting Started with Unity Shader - Transparency Effect
Selenium自动化中无头浏览器的应用
SetoolKit User Guide
Analysis of the startup source code of hyperf (2) - how the request reaches the controller
LeetCode二叉树系列——110.平衡二叉树
2021 OWASP TOP 10 Vulnerability Guide
R语言ggplot2可视化:使用ggpubr包的ggboxplot函数可视化分组箱图、使用ggpar函数改变图形化参数(caption、添加、修改可视化图像的题注、脚注内容)