RecycleView+卡片+下拉刷新

1.添加依赖

 implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.0.0'
    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"

2.主界面

package com.example.myapplication3



import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout

class MainActivity : AppCompatActivity() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var swipe_view: SwipeRefreshLayout
    private lateinit var viewAdapter: RecyclerView.Adapter<*>
    private lateinit var viewManager: RecyclerView.LayoutManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main);

        val myDataset = mutableListOf()
        for (i in 0 until 20) {
            myDataset.add(i.toString())
        }
        viewManager = LinearLayoutManager(this)
        viewAdapter = MyAdapter(myDataset)
        recyclerView = findViewById(R.id.recycle_view).apply {
            setHasFixedSize(true)
            layoutManager = viewManager
            adapter = viewAdapter
        }

        swipe_view = findViewById(R.id.swipe_view)
        swipe_view.setColorSchemeColors(resources.getColor(R.color.white))
        swipe_view.setProgressBackgroundColorSchemeResource(R.color.gray)
        swipe_view.setOnRefreshListener {
            //your code Handler
            Handler().postDelayed({ swipe_view.isRefreshing = false }, 2000)
        }
    }


}

 

3.适配器

package com.example.myapplication3


import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

class MyAdapter(private val myDataset: MutableList) : RecyclerView.Adapter() {


    class MyViewHolder(v: View) : RecyclerView.ViewHolder(v) {
        val textView: TextView

        init {
            v.setOnClickListener { Log.e("TAG", "$adapterPosition") }
            textView = v.findViewById(R.id.textViews)
        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.layout_item, parent, false);
        return MyViewHolder(v)
    }

    override fun getItemCount(): Int {
        return myDataset.size
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.textView.text = myDataset[position];
    }

    companion object {
        private val TAG = "CustomAdapter"
    }
}

4.主界面布局:




    


5.item布局




    



6.color资源

   #fff
    #999

运行效果:

RecycleView+卡片+下拉刷新_第1张图片

你可能感兴趣的:(kotlin学习)