Android Kotlin-----RecyclerView的使用

程序中需要注意几点:

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

    

部分代码如下:

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

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

Model层:

    Category.kt 代码:

class Category(val title:String,val image:String){
    override fun toString(): String {
        return title
    }
}//定义类型类

    Product.kt 代码:

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

Control层:

   MainActivity.kt 代码:

class MainActivity : AppCompatActivity() {

    //lateinit var adapter:CategoryAdapter
    lateinit var adapter:CategoryRecycleAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //adapter= CategoryAdapter(this,DataService.categories)
        //categoryListView.adapter=adapter

        //列表每一条的点击事件
        adapter= CategoryRecycleAdapter(this,DataService.categories){
            category ->
            val productIntent=Intent(this,ProductActivity::class.java)
            productIntent.putExtra(EXTRA_CATEGORY,category.title)
            startActivity(productIntent)
        }
        categoryListView.adapter=adapter

        val layoutManager=LinearLayoutManager(this)
        categoryListView.layoutManager=layoutManager
        categoryListView.setHasFixedSize(true)
    }
}

   ProductActivity.kt 代码:

class ProductActivity : AppCompatActivity() {
    lateinit var adater:ProductAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_product)

        val categroyType=intent.getStringExtra(EXTRA_CATEGORY)//传递值
        Toast.makeText(this,"$categroyType",Toast.LENGTH_LONG).show()
        adater=ProductAdapter(this,DataService.getProduct(categroyType))

        var spanCount=2
        val screenSize=resources.configuration.screenWidthDp
        if(screenSize >720){   //适应大的屏幕
            spanCount=3
        }

        val layoutManager=GridLayoutManager(this,2) //每行两列的网格布局
        productsListView.layoutManager=layoutManager
        productsListView.adapter=adater
    }
}

Adapter层:

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

class CategoryAdapter(val context: Context, val categories: List<Category>): BaseAdapter() {

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val categoryView:View
        val holder:ViewHolder

        if(convertView==null) {
            //获取布局文件   显示布局变成默认包裹内容
            categoryView = LayoutInflater.from(context).inflate(R.layout.category_list_item, null)
            holder= ViewHolder()
            holder.categoryImage = categoryView.findViewById(R.id.categoryImage)//获取id
            holder.categoryName= categoryView.findViewById(R.id.categoryName)
            categoryView.tag=holder     //tag:存储一些view的数据
        }else{
            //当convertView不为空的时候直接重新使用convertView从而减少了很多不必要的View的创建,然后加载数据
            holder=convertView.tag as ViewHolder   //as:强制转换类型
            categoryView=convertView
        }
        val category=categories[position]   //获取类别的位置
        //获取资源文件中指定的图片    getIdentifier()方法可以方便的获各应用包下的指定资源ID
        val resourceId=context.resources.getIdentifier(category.image,"drawable",context.packageName)
        holder.categoryImage?.setImageResource(resourceId)

        holder.categoryName?.text=category.title    //获取标题
        return categoryView
    }

    override fun getItem(position: Int): Any {
        return categories[position]
    }

    override fun getItemId(position: Int): Long {
        return 0
    }

    override fun getCount(): Int {
        return categories.count()
    }
    private class ViewHolder{
        //不必每次加载都到布局文件中去拿View,提高了效率
        var categoryImage:ImageView?=null
        var categoryName:TextView?=null
    }
}

    CategoryRecycleAdapter.kt 代码:

class CategoryRecycleAdapter(val context:Context,val categories:List<Category>,val itemClick:(Category) ->Unit) :RecyclerView.Adapter<CategoryRecycleAdapter.Holder>() {

    //onCreateViewHolder():是用来配合写好的ViewHolder来返回一个ViewHolder对象。这里也涉及到了条目布局的加载。
    //viewType则表示需要给当前position生成的是哪一种ViewHolder,这个参数也说明了RecyclerView对多类型ItemView的支持。
    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): Holder {
        val view=LayoutInflater.from(context).inflate(R.layout.category_list_item,parent,false)
        return Holder(view,itemClick)
    }

    override fun getItemCount(): Int {
        return categories.count()
    }

    //专门用来绑定ViewHolder里的控件和数据源中position位置的数据。
    override fun onBindViewHolder(holder: Holder?, position: Int) {
        holder?.bindCategory(categories[position],context)
    }

     //定义内部类Holder
    inner class Holder(itemView:View?,val itemClick:(Category) ->Unit): RecyclerView.ViewHolder(itemView){

        val categoryImage=itemView?.findViewById<ImageView>(R.id.categoryImage)
        val categoryName=itemView?.findViewById<TextView>(R.id.categoryName)

        fun bindCategory(category: Category,context: Context){
            val resourceId=context.resources.getIdentifier(category.image,"drawable",context.packageName)
            categoryImage?.setImageResource(resourceId)
            categoryName?.text=category.title
            itemView.setOnClickListener { itemClick(category) }
        }
    }
}

    ProductAdapter.kt 代码:

class ProductAdapter(val context: Context,val products:List<Product>):RecyclerView.Adapter<ProductAdapter.ProductHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ProductHolder {
        val view=LayoutInflater.from(context).inflate(R.layout.product_list_item,parent,false)
        return ProductHolder(view)
    }

    override fun getItemCount(): Int {
        return products.count()
    }

    override fun onBindViewHolder(holder: ProductHolder?, position: Int) {
        holder?.bindProduct(products[position],context)
    }


    inner class ProductHolder(itemView:View?):RecyclerView.ViewHolder(itemView){

        val productImage=itemView?.findViewById<ImageView>(R.id.productImage)
        val productName=itemView?.findViewById<TextView>(R.id.categoryName)
        val productPrice=itemView?.findViewById<TextView>(R.id.productPrice)

        fun bindProduct(products: Product,context: Context){
            val resourcesProductId=context.resources.getIdentifier(products.image,"drawable",context.packageName)
            productImage?.setImageResource(resourcesProductId)
            productName?.text=products.title
            productPrice?.text=products.price
        }
    }
}

Services层:

    DataService.kt 代码:

object DataService {
    val categories= listOf(
            Category("衬衫","shirtimage"),
            Category("卫衣","hoodieimage"),
            Category("帽子","hatimage"),
            Category("数码产品","digitalgoodsimage"),
            Category("衬衫","shirtimage"),
            Category("卫衣","hoodieimage"),
            Category("帽子","hatimage"),
            Category("数码产品","digitalgoodsimage"),
            Category("衬衫","shirtimage"),
            Category("卫衣","hoodieimage"),
            Category("帽子","hatimage"),
            Category("数码产品","digitalgoodsimage")
    )

    val hats= listOf(
            Product("Devslopes Graphic Beanie","$18","hat1"),
            Product("Devslopes Hat Black","$20","hat2"),
            Product("Devslopes Hat White","$18","hat3"),
            Product("Devslopes Hat Snapback","$22","hat4"),
            Product("Devslopes Graphic Beanie","$18","hat1"),
            Product("Devslopes Hat Black","$20","hat2"),
            Product("Devslopes Hat White","$18","hat3"),
            Product("Devslopes Hat Snapback","$22","hat4"),
            Product("Devslopes Graphic Beanie","$18","hat1"),
            Product("Devslopes Hat Black","$20","hat2"),
            Product("Devslopes Hat White","$18","hat3"),
            Product("Devslopes Hat Snapback","$22","hat4"),
            Product("Devslopes Graphic Beanie","$18","hat1"),
            Product("Devslopes Hat Black","$20","hat2"),
            Product("Devslopes Hat White","$18","hat3"),
            Product("Devslopes Hat Snapback","$22","hat4")
    )

    val hoodies= listOf(
            Product("Devslopes Hoodie Gray","$28","hoodie1"),
            Product("Devslopes Hoodie Red","$32","hoodie2"),
            Product("Devslopes Gray Hoodie","$28","hoodie3"),
            Product("Devslopes Black Hoodie","$32","hoodie4"),
            Product("Devslopes Hoodie Gray","$28","hoodie1"),
            Product("Devslopes Hoodie Red","$32","hoodie2"),
            Product("Devslopes Gray Hoodie","$28","hoodie3"),
            Product("Devslopes Black Hoodie","$32","hoodie4"),
            Product("Devslopes Hoodie Gray","$28","hoodie1"),
            Product("Devslopes Hoodie Red","$32","hoodie2"),
            Product("Devslopes Gray Hoodie","$28","hoodie3"),
            Product("Devslopes Black Hoodie","$32","hoodie4"),
            Product("Devslopes Hoodie Gray","$28","hoodie1"),
            Product("Devslopes Hoodie Red","$32","hoodie2"),
            Product("Devslopes Gray Hoodie","$28","hoodie3"),
            Product("Devslopes Black Hoodie","$32","hoodie4"),
            Product("Devslopes Hoodie Gray","$28","hoodie1"),
            Product("Devslopes Hoodie Red","$32","hoodie2"),
            Product("Devslopes Gray Hoodie","$28","hoodie3"),
            Product("Devslopes Black Hoodie","$32","hoodie4"),
            Product("Devslopes Hoodie Gray","$28","hoodie1"),
            Product("Devslopes Hoodie Red","$32","hoodie2"),
            Product("Devslopes Gray Hoodie","$28","hoodie3"),
            Product("Devslopes Black Hoodie","$32","hoodie4")
    )

    val shirts= listOf(
            Product("Devslopes Shirt Black","$18","shirt1"),
            Product("Devslopes Badge Light Gray","$20","shirt2"),
            Product("Devslopes Logo Shirt Red","$22","shirt3"),
            Product("Devslopes Hustle","$22","shirt4"),
            Product("Kickflip","$18","shirt5"),
            Product("Devslopes Shirt Black","$18","shirt1"),
            Product("Devslopes Badge Light Gray","$20","shirt2"),
            Product("Devslopes Logo Shirt Red","$22","shirt3"),
            Product("Devslopes Hustle","$22","shirt4"),
            Product("Kickflip","$18","shirt5"),
            Product("Devslopes Shirt Black","$18","shirt1"),
            Product("Devslopes Badge Light Gray","$20","shirt2"),
            Product("Devslopes Logo Shirt Red","$22","shirt3"),
            Product("Devslopes Hustle","$22","shirt4"),
            Product("Kickflip","$18","shirt5"),
            Product("Devslopes Shirt Black","$18","shirt1"),
            Product("Devslopes Badge Light Gray","$20","shirt2"),
            Product("Devslopes Logo Shirt Red","$22","shirt3"),
            Product("Devslopes Hustle","$22","shirt4"),
            Product("Kickflip","$18","shirt5")
    )

    val digitalGood= listOf<Product>()   //空的数码产品
    fun getProduct(category:String):List<Product>{       //根据类型获取商品
        return when(category){
            "衬衫"-> shirts
            "帽子"-> hats
            "卫衣"-> hoodies
            else -> digitalGood
        }
    }}

Utility层:

    Contents.kt  代码:

const val EXTRA_CATEGORY="category"

View层:

    activity_main.xml 代码:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.dpl.coderswag.Controller.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:text="种类"
        android:textSize="18sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/categoryListView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:divider="@null"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="1.0" />

</android.support.constraint.ConstraintLayout>

activity_product.xml 代码:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    tools:context="com.example.dpl.coderswag.Controller.ProductActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:text="产品"
        android:textSize="18sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/productsListView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:divider="@null"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="1.0" />

</android.support.constraint.ConstraintLayout>

category_list_item.xml 代码:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:layout_width="match_parent"
    android:layout_height="166dp">

    <ImageView
        android:id="@+id/categoryImage"
        android:layout_width="0dp"
        android:layout_height="150dp"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:scaleType="centerCrop"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@drawable/hatimage" />

    <TextView
        android:id="@+id/categoryName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="HATS"
        android:textColor="@android:color/white"
        android:textSize="24sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="@+id/categoryImage"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

product_list_item.xml 代码:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/productImage"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintDimensionRatio="w,1:1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/hat1" />

    <TextView
        android:id="@+id/productName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:textAlignment="center"
        android:textSize="18sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/productImage"
        tools:text="帽子A" />

    <TextView
        android:id="@+id/productPrice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:textSize="14sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/productName"
        tools:text="¥30" />
</android.support.constraint.ConstraintLayout>

运行效果:



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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值