当前位置:   article > 正文

Android Kotlin-----RecyclerView的使用_android kotlin recyclerview

android kotlin recyclerview

程序中需要注意几点:

       MVC的设计模式、RecyclerView库的使用......

    

部分代码如下:

  首先在build.gradle(app)中添加RecyclerView库的依赖:

compile 'com.android.support:recyclerview-v7:26.1.0'

Model层:

    Category.kt 代码:

  1. class Category(val title:String,val image:String){
  2. override fun toString(): String {
  3. return title
  4. }
  5. }//定义类型类

    Product.kt 代码:

class Product(val title:String,val price:String,val image:String)  //定义产品类

Control层:

   MainActivity.kt 代码:

  1. class MainActivity : AppCompatActivity() {
  2. //lateinit var adapter:CategoryAdapter
  3. lateinit var adapter:CategoryRecycleAdapter
  4. override fun onCreate(savedInstanceState: Bundle?) {
  5. super.onCreate(savedInstanceState)
  6. setContentView(R.layout.activity_main)
  7. //adapter= CategoryAdapter(this,DataService.categories)
  8. //categoryListView.adapter=adapter
  9. //列表每一条的点击事件
  10. adapter= CategoryRecycleAdapter(this,DataService.categories){
  11. category ->
  12. val productIntent=Intent(this,ProductActivity::class.java)
  13. productIntent.putExtra(EXTRA_CATEGORY,category.title)
  14. startActivity(productIntent)
  15. }
  16. categoryListView.adapter=adapter
  17. val layoutManager=LinearLayoutManager(this)
  18. categoryListView.layoutManager=layoutManager
  19. categoryListView.setHasFixedSize(true)
  20. }
  21. }

   ProductActivity.kt 代码:

  1. class ProductActivity : AppCompatActivity() {
  2. lateinit var adater:ProductAdapter
  3. override fun onCreate(savedInstanceState: Bundle?) {
  4. super.onCreate(savedInstanceState)
  5. setContentView(R.layout.activity_product)
  6. val categroyType=intent.getStringExtra(EXTRA_CATEGORY)//传递值
  7. Toast.makeText(this,"$categroyType",Toast.LENGTH_LONG).show()
  8. adater=ProductAdapter(this,DataService.getProduct(categroyType))
  9. var spanCount=2
  10. val screenSize=resources.configuration.screenWidthDp
  11. if(screenSize >720){ //适应大的屏幕
  12. spanCount=3
  13. }
  14. val layoutManager=GridLayoutManager(this,2) //每行两列的网格布局
  15. productsListView.layoutManager=layoutManager
  16. productsListView.adapter=adater
  17. }
  18. }

Adapter层:

   CategoryAdapter.kt(ListView的适配器,程序中被代替了,没有用到)

  1. class CategoryAdapter(val context: Context, val categories: List<Category>): BaseAdapter() {
  2. override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
  3. val categoryView:View
  4. val holder:ViewHolder
  5. if(convertView==null) {
  6. //获取布局文件 显示布局变成默认包裹内容
  7. categoryView = LayoutInflater.from(context).inflate(R.layout.category_list_item, null)
  8. holder= ViewHolder()
  9. holder.categoryImage = categoryView.findViewById(R.id.categoryImage)//获取id
  10. holder.categoryName= categoryView.findViewById(R.id.categoryName)
  11. categoryView.tag=holder //tag:存储一些view的数据
  12. }else{
  13. //当convertView不为空的时候直接重新使用convertView从而减少了很多不必要的View的创建,然后加载数据
  14. holder=convertView.tag as ViewHolder //as:强制转换类型
  15. categoryView=convertView
  16. }
  17. val category=categories[position] //获取类别的位置
  18. //获取资源文件中指定的图片 getIdentifier()方法可以方便的获各应用包下的指定资源ID
  19. val resourceId=context.resources.getIdentifier(category.image,"drawable",context.packageName)
  20. holder.categoryImage?.setImageResource(resourceId)
  21. holder.categoryName?.text=category.title //获取标题
  22. return categoryView
  23. }
  24. override fun getItem(position: Int): Any {
  25. return categories[position]
  26. }
  27. override fun getItemId(position: Int): Long {
  28. return 0
  29. }
  30. override fun getCount(): Int {
  31. return categories.count()
  32. }
  33. private class ViewHolder{
  34. //不必每次加载都到布局文件中去拿View,提高了效率
  35. var categoryImage:ImageView?=null
  36. var categoryName:TextView?=null
  37. }
  38. }

    CategoryRecycleAdapter.kt 代码:

  1. class CategoryRecycleAdapter(val context:Context,val categories:List<Category>,val itemClick:(Category) ->Unit) :RecyclerView.Adapter<CategoryRecycleAdapter.Holder>() {
  2. //onCreateViewHolder():是用来配合写好的ViewHolder来返回一个ViewHolder对象。这里也涉及到了条目布局的加载。
  3. //viewType则表示需要给当前position生成的是哪一种ViewHolder,这个参数也说明了RecyclerView对多类型ItemView的支持。
  4. override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): Holder {
  5. val view=LayoutInflater.from(context).inflate(R.layout.category_list_item,parent,false)
  6. return Holder(view,itemClick)
  7. }
  8. override fun getItemCount(): Int {
  9. return categories.count()
  10. }
  11. //专门用来绑定ViewHolder里的控件和数据源中position位置的数据。
  12. override fun onBindViewHolder(holder: Holder?, position: Int) {
  13. holder?.bindCategory(categories[position],context)
  14. }
  15. //定义内部类Holder
  16. inner class Holder(itemView:View?,val itemClick:(Category) ->Unit): RecyclerView.ViewHolder(itemView){
  17. val categoryImage=itemView?.findViewById<ImageView>(R.id.categoryImage)
  18. val categoryName=itemView?.findViewById<TextView>(R.id.categoryName)
  19. fun bindCategory(category: Category,context: Context){
  20. val resourceId=context.resources.getIdentifier(category.image,"drawable",context.packageName)
  21. categoryImage?.setImageResource(resourceId)
  22. categoryName?.text=category.title
  23. itemView.setOnClickListener { itemClick(category) }
  24. }
  25. }
  26. }

    ProductAdapter.kt 代码:

  1. class ProductAdapter(val context: Context,val products:List<Product>):RecyclerView.Adapter<ProductAdapter.ProductHolder>() {
  2. override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ProductHolder {
  3. val view=LayoutInflater.from(context).inflate(R.layout.product_list_item,parent,false)
  4. return ProductHolder(view)
  5. }
  6. override fun getItemCount(): Int {
  7. return products.count()
  8. }
  9. override fun onBindViewHolder(holder: ProductHolder?, position: Int) {
  10. holder?.bindProduct(products[position],context)
  11. }
  12. inner class ProductHolder(itemView:View?):RecyclerView.ViewHolder(itemView){
  13. val productImage=itemView?.findViewById<ImageView>(R.id.productImage)
  14. val productName=itemView?.findViewById<TextView>(R.id.categoryName)
  15. val productPrice=itemView?.findViewById<TextView>(R.id.productPrice)
  16. fun bindProduct(products: Product,context: Context){
  17. val resourcesProductId=context.resources.getIdentifier(products.image,"drawable",context.packageName)
  18. productImage?.setImageResource(resourcesProductId)
  19. productName?.text=products.title
  20. productPrice?.text=products.price
  21. }
  22. }
  23. }

Services层:

    DataService.kt 代码:

  1. object DataService {
  2. val categories= listOf(
  3. Category("衬衫","shirtimage"),
  4. Category("卫衣","hoodieimage"),
  5. Category("帽子","hatimage"),
  6. Category("数码产品","digitalgoodsimage"),
  7. Category("衬衫","shirtimage"),
  8. Category("卫衣","hoodieimage"),
  9. Category("帽子","hatimage"),
  10. Category("数码产品","digitalgoodsimage"),
  11. Category("衬衫","shirtimage"),
  12. Category("卫衣","hoodieimage"),
  13. Category("帽子","hatimage"),
  14. Category("数码产品","digitalgoodsimage")
  15. )
  16. val hats= listOf(
  17. Product("Devslopes Graphic Beanie","$18","hat1"),
  18. Product("Devslopes Hat Black","$20","hat2"),
  19. Product("Devslopes Hat White","$18","hat3"),
  20. Product("Devslopes Hat Snapback","$22","hat4"),
  21. Product("Devslopes Graphic Beanie","$18","hat1"),
  22. Product("Devslopes Hat Black","$20","hat2"),
  23. Product("Devslopes Hat White","$18","hat3"),
  24. Product("Devslopes Hat Snapback","$22","hat4"),
  25. Product("Devslopes Graphic Beanie","$18","hat1"),
  26. Product("Devslopes Hat Black","$20","hat2"),
  27. Product("Devslopes Hat White","$18","hat3"),
  28. Product("Devslopes Hat Snapback","$22","hat4"),
  29. Product("Devslopes Graphic Beanie","$18","hat1"),
  30. Product("Devslopes Hat Black","$20","hat2"),
  31. Product("Devslopes Hat White","$18","hat3"),
  32. Product("Devslopes Hat Snapback","$22","hat4")
  33. )
  34. val hoodies= listOf(
  35. Product("Devslopes Hoodie Gray","$28","hoodie1"),
  36. Product("Devslopes Hoodie Red","$32","hoodie2"),
  37. Product("Devslopes Gray Hoodie","$28","hoodie3"),
  38. Product("Devslopes Black Hoodie","$32","hoodie4"),
  39. Product("Devslopes Hoodie Gray","$28","hoodie1"),
  40. Product("Devslopes Hoodie Red","$32","hoodie2"),
  41. Product("Devslopes Gray Hoodie","$28","hoodie3"),
  42. Product("Devslopes Black Hoodie","$32","hoodie4"),
  43. Product("Devslopes Hoodie Gray","$28","hoodie1"),
  44. Product("Devslopes Hoodie Red","$32","hoodie2"),
  45. Product("Devslopes Gray Hoodie","$28","hoodie3"),
  46. Product("Devslopes Black Hoodie","$32","hoodie4"),
  47. Product("Devslopes Hoodie Gray","$28","hoodie1"),
  48. Product("Devslopes Hoodie Red","$32","hoodie2"),
  49. Product("Devslopes Gray Hoodie","$28","hoodie3"),
  50. Product("Devslopes Black Hoodie","$32","hoodie4"),
  51. Product("Devslopes Hoodie Gray","$28","hoodie1"),
  52. Product("Devslopes Hoodie Red","$32","hoodie2"),
  53. Product("Devslopes Gray Hoodie","$28","hoodie3"),
  54. Product("Devslopes Black Hoodie","$32","hoodie4"),
  55. Product("Devslopes Hoodie Gray","$28","hoodie1"),
  56. Product("Devslopes Hoodie Red","$32","hoodie2"),
  57. Product("Devslopes Gray Hoodie","$28","hoodie3"),
  58. Product("Devslopes Black Hoodie","$32","hoodie4")
  59. )
  60. val shirts= listOf(
  61. Product("Devslopes Shirt Black","$18","shirt1"),
  62. Product("Devslopes Badge Light Gray","$20","shirt2"),
  63. Product("Devslopes Logo Shirt Red","$22","shirt3"),
  64. Product("Devslopes Hustle","$22","shirt4"),
  65. Product("Kickflip","$18","shirt5"),
  66. Product("Devslopes Shirt Black","$18","shirt1"),
  67. Product("Devslopes Badge Light Gray","$20","shirt2"),
  68. Product("Devslopes Logo Shirt Red","$22","shirt3"),
  69. Product("Devslopes Hustle","$22","shirt4"),
  70. Product("Kickflip","$18","shirt5"),
  71. Product("Devslopes Shirt Black","$18","shirt1"),
  72. Product("Devslopes Badge Light Gray","$20","shirt2"),
  73. Product("Devslopes Logo Shirt Red","$22","shirt3"),
  74. Product("Devslopes Hustle","$22","shirt4"),
  75. Product("Kickflip","$18","shirt5"),
  76. Product("Devslopes Shirt Black","$18","shirt1"),
  77. Product("Devslopes Badge Light Gray","$20","shirt2"),
  78. Product("Devslopes Logo Shirt Red","$22","shirt3"),
  79. Product("Devslopes Hustle","$22","shirt4"),
  80. Product("Kickflip","$18","shirt5")
  81. )
  82. val digitalGood= listOf<Product>() //空的数码产品
  83. fun getProduct(category:String):List<Product>{ //根据类型获取商品
  84. return when(category){
  85. "衬衫"-> shirts
  86. "帽子"-> hats
  87. "卫衣"-> hoodies
  88. else -> digitalGood
  89. }
  90. }}

Utility层:

    Contents.kt  代码:

const val EXTRA_CATEGORY="category"

View层:

    activity_main.xml 代码:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. tools:context="com.example.dpl.coderswag.Controller.MainActivity">
  8. <TextView
  9. android:id="@+id/textView"
  10. android:layout_width="wrap_content"
  11. android:layout_height="wrap_content"
  12. android:layout_marginStart="16dp"
  13. android:layout_marginTop="16dp"
  14. android:text="种类"
  15. android:textSize="18sp"
  16. app:layout_constraintStart_toStartOf="parent"
  17. app:layout_constraintTop_toTopOf="parent" />
  18. <android.support.v7.widget.RecyclerView
  19. android:id="@+id/categoryListView"
  20. android:layout_width="0dp"
  21. android:layout_height="0dp"
  22. android:layout_marginTop="16dp"
  23. android:divider="@null"
  24. app:layout_constraintBottom_toBottomOf="parent"
  25. app:layout_constraintEnd_toEndOf="parent"
  26. app:layout_constraintHorizontal_bias="0.0"
  27. app:layout_constraintStart_toStartOf="parent"
  28. app:layout_constraintTop_toBottomOf="@+id/textView"
  29. app:layout_constraintVertical_bias="1.0" />
  30. </android.support.constraint.ConstraintLayout>

activity_product.xml 代码:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:background="@android:color/white"
  8. tools:context="com.example.dpl.coderswag.Controller.ProductActivity">
  9. <TextView
  10. android:id="@+id/textView"
  11. android:layout_width="wrap_content"
  12. android:layout_height="wrap_content"
  13. android:layout_marginStart="16dp"
  14. android:layout_marginTop="16dp"
  15. android:text="产品"
  16. android:textSize="18sp"
  17. app:layout_constraintStart_toStartOf="parent"
  18. app:layout_constraintTop_toTopOf="parent" />
  19. <android.support.v7.widget.RecyclerView
  20. android:id="@+id/productsListView"
  21. android:layout_width="0dp"
  22. android:layout_height="0dp"
  23. android:layout_marginTop="16dp"
  24. android:divider="@null"
  25. app:layout_constraintBottom_toBottomOf="parent"
  26. app:layout_constraintEnd_toEndOf="parent"
  27. app:layout_constraintHorizontal_bias="0.0"
  28. app:layout_constraintStart_toStartOf="parent"
  29. app:layout_constraintTop_toBottomOf="@+id/textView"
  30. app:layout_constraintVertical_bias="1.0" />
  31. </android.support.constraint.ConstraintLayout>

category_list_item.xml 代码:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <android.support.constraint.ConstraintLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. xmlns:app="http://schemas.android.com/apk/res-auto"
  5. xmlns:tools="http://schemas.android.com/tools"
  6. android:layout_width="match_parent"
  7. android:layout_height="166dp">
  8. <ImageView
  9. android:id="@+id/categoryImage"
  10. android:layout_width="0dp"
  11. android:layout_height="150dp"
  12. android:layout_marginBottom="8dp"
  13. android:layout_marginTop="8dp"
  14. android:scaleType="centerCrop"
  15. app:layout_constraintBottom_toBottomOf="parent"
  16. app:layout_constraintEnd_toEndOf="parent"
  17. app:layout_constraintStart_toStartOf="parent"
  18. app:layout_constraintTop_toTopOf="parent"
  19. tools:srcCompat="@drawable/hatimage" />
  20. <TextView
  21. android:id="@+id/categoryName"
  22. android:layout_width="wrap_content"
  23. android:layout_height="wrap_content"
  24. android:layout_marginBottom="8dp"
  25. android:layout_marginEnd="8dp"
  26. android:layout_marginStart="8dp"
  27. android:layout_marginTop="8dp"
  28. android:text="HATS"
  29. android:textColor="@android:color/white"
  30. android:textSize="24sp"
  31. android:textStyle="bold"
  32. app:layout_constraintBottom_toBottomOf="@+id/categoryImage"
  33. app:layout_constraintEnd_toEndOf="parent"
  34. app:layout_constraintStart_toStartOf="parent"
  35. app:layout_constraintTop_toTopOf="parent" />
  36. </android.support.constraint.ConstraintLayout>

product_list_item.xml 代码:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <android.support.constraint.ConstraintLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. xmlns:app="http://schemas.android.com/apk/res-auto"
  5. xmlns:tools="http://schemas.android.com/tools"
  6. android:layout_width="match_parent"
  7. android:layout_height="wrap_content">
  8. <ImageView
  9. android:id="@+id/productImage"
  10. android:layout_width="0dp"
  11. android:layout_height="0dp"
  12. android:layout_marginEnd="8dp"
  13. android:layout_marginStart="8dp"
  14. android:layout_marginTop="8dp"
  15. app:layout_constraintDimensionRatio="w,1:1"
  16. app:layout_constraintEnd_toEndOf="parent"
  17. app:layout_constraintStart_toStartOf="parent"
  18. app:layout_constraintTop_toTopOf="parent"
  19. app:srcCompat="@drawable/hat1" />
  20. <TextView
  21. android:id="@+id/productName"
  22. android:layout_width="0dp"
  23. android:layout_height="wrap_content"
  24. android:layout_marginEnd="16dp"
  25. android:layout_marginStart="16dp"
  26. android:layout_marginTop="8dp"
  27. android:textAlignment="center"
  28. android:textSize="18sp"
  29. app:layout_constraintEnd_toEndOf="parent"
  30. app:layout_constraintStart_toStartOf="parent"
  31. app:layout_constraintTop_toBottomOf="@+id/productImage"
  32. tools:text="帽子A" />
  33. <TextView
  34. android:id="@+id/productPrice"
  35. android:layout_width="wrap_content"
  36. android:layout_height="wrap_content"
  37. android:layout_marginBottom="8dp"
  38. android:layout_marginEnd="8dp"
  39. android:layout_marginStart="8dp"
  40. android:layout_marginTop="8dp"
  41. android:textSize="14sp"
  42. app:layout_constraintBottom_toBottomOf="parent"
  43. app:layout_constraintEnd_toEndOf="parent"
  44. app:layout_constraintStart_toStartOf="parent"
  45. app:layout_constraintTop_toBottomOf="@+id/productName"
  46. tools:text="¥30" />
  47. </android.support.constraint.ConstraintLayout>

运行效果:



程序源码: https://github.com/dpl12/CoderSwag


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/787397
推荐阅读
相关标签
  

闽ICP备14008679号