当前位置:网站首页>Efficient use of RecyclerView Section 1
Efficient use of RecyclerView Section 1
2022-07-31 14:56:00 【[email protected]】
List-related layouts are the most integral part of the development process,And mastering some efficient skills can help us improve development efficiency at the same time,还能优化代码,Reduce redundancy andbug的产生.
1.listitem实时预览
在UI绘制时,Detail and style adjustments are unavoidable,If every adjustment goesrunCheck the effect later,inefficiency,使用listitem,operation can be avoided,直接使用AndroidStudioBuilt-in preview function for debugging
例如
<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" />
It can be set directly in the layout codeLayoutManagertype and some related properties,例如方向,The number of each row in grid layout, etc.
3,Use the default dividing line
You can use the default split line style provided by the official,Reduce duplicate creation.
//添加默认的分割线
rv_student.addItemDecoration(DividerItemDecoration(this,
(rv_student.layoutManager as LinearLayoutManager).orientation))
For personalization,need to base itself onItemDecoration进行定制
4,添加Item点击事件
使用Kotlin函数式的思想,Quickly add click events
1)在Adapteradd parameters to the constructor
class StudentAdapter(private val data:ArrayList<StudentInfo>,
private val itemClick:(StudentInfo) ->Unit):
RecyclerView.Adapter<StudentAdapter.ViewHolder>() {
}
2)初始化AdapterWhen passing in the click function
//学生数据列表
private val studentEntities = ArrayList<StudentInfo>()
//适配器
private val studentAdapter by lazy {
StudentAdapter(studentEntities,this::onStudentItemClick)
}
/**
*点击事件
*/
private fun onStudentItemClick(entity:StudentInfo){
/**
* 点击Item时,Get the user information of the current click
*/
Log.d(TAG,"onStudentItemClick()--->$entity")
Toast.makeText(this,"$entity",Toast.LENGTH_LONG).show()
}
3)使用时
itemView.setOnClickListener { itemClick(entity) }
5,Adapter中获取上下文
在onCreateViewHolder中获取context对象,Reduce the number of parameters passed during construction
//定义上下文
private lateinit var context:Context
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
context = parent.context
}
The code that completes the above function is as follows:
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时,Get the user information of the current click
*/
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
}
}
}
}
针对RecyclerViewThis is what has been learned so far in relation to practical use,The specific practice also needs to be optimized and implemented in combination with its own project structure.
RecyclerViewis essential for development,Although its features and performance compare toListViewThere have been great improvements and enhancements,However, there are still some performance problems when used improperly,And there is still room for further optimization,结合mCacheViewExtension和DiffUtil的实现,让你的UI更加流畅.
版权声明
本文为[[email protected]]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/212/202207311451011633.html
边栏推荐
- NC | 中国农大草业学院杨高文组揭示发现多因子干扰会降低土壤微生物多样性的积极效应...
- Synchronized和volatile 面试简单汇总
- ML, DL, CV common problems sorting
- OpenShift 4 - 用 Operator 部署 Redis 集群
- 五个维度着手MySQL的优化
- OAuth2:使用JWT令牌
- element-plus虚拟表格virtual-list组件中是怎么实现清理lodash.memoize缓存的?
- Message queue data storage MySQL table design
- 【CUDA学习笔记】初识CUDA
- 谷歌CTS测试(cta测试)
猜你喜欢

TRACE32——基于SNOOPer的变量记录

LeetCode二叉树系列——222.完全二叉树的节点个数

OAuth2:单点登陆客户端

Redis与分布式:集群搭建

Ubantu专题4:xshell、xftp连接接虚拟机以及设置xshell复制粘贴快捷键

STM32(十)------- SPI通信

以后面试官问你 为啥不建议使用Select *,请你大声回答他!

Asynchronous processing business using CompletableFuture

abaqus find contact pairs报错:surface name is already in use

五个维度着手MySQL的优化
随机推荐
深入浅出边缘云 | 4. 生命周期管理
OAuth2:搭建授权服务器
OAuth2:资源服务器
R语言的画图代码及差异性分析[通俗易懂]
模板与泛型编程值typelist实现
Network cable RJ45 interface pins [easy to understand]
R语言计算时间序列数据的移动平均值(滚动平均值、例如5日均线、10日均线等):使用zoo包中的rollmean函数计算k个周期移动平均值
/etc/profile、/etc/bashrc、~/.bash_profile、~/.bashrc 文件的作用
MySQL 23道经典面试吊打面试官
R语言ggplot2可视化:使用ggpubr包的ggmaplot函数可视化MA图(MA-plot)、font.legend参数和font.main参数设置标题和图例字体加粗
Introductory UnityShader learning (2) - the rendering pipeline
SetoolKit User Guide
易驱线主控芯片对比(电动三轮电机90O瓦世纪通达)
OpenShift 4 - 定制 RHACS 安全策略,阻断生产集群使用高风险 Registry
LeetCode二叉树系列——110.平衡二叉树
OAuth2:微服务权限校验Session共享
四象限时间管理有多好用?
OAuth2:使用JWT令牌
435. 无重叠区间
OpenCV测量物体的尺寸技能 get~