日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Kotlin使用滾動控件RecyclerView實例教程_Android

作者:Hdnw ? 更新時間: 2022-12-29 編程語言

1.RecyclerView介紹

  • RecyclerView是一個增強版的ListView(Android 5.0推出)。
  • 被用來代替ListView和GridView控件,并且能夠實現瀑布流的布局。
  • 它更加高級并且更加靈活·,可提供更為高效的回收復用機制,同時實現管理與視圖的解耦合。

2.RecyclerView控件的使用

步驟: 在項目的build.gradle中添加RecyclerView庫的依賴。

implementation 'androidx.recyclerview:recyclerview:1.2.1'

在布局中加入RecyclerView控件和為RecyclerView的子項指定一個我們自定義的布局。

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="60dp">
     <ImageView
         android:id="@+id/fruitImage"
         android:layout_width="40dp"
         android:layout_height="40dp"
         android:layout_gravity="center_horizontal"
         android:layout_marginTop="10dp"
         />
    <TextView
        android:id="@+id/fruitName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"/>
</LinearLayout>

自定義RecyclerView.Adapter適配器

  • 要創建一個Adapter類,該類繼承于RecyclerView.Adapter<VH>,其中VH是我們在Adapter類中創建的一個繼承于RecyclerView.ViewHolder的內部類。
  • 該Adapter類主要有3個方法和一個自定義ViewHolder組成。

(1)onCreateViewHolder:創建ViewHolder并返回,后續item布局里控件都是從ViewHolder中取出

(2)onBindViewHolder:通過方法提供ViewHolder,將數據綁定到ViewHolder。

(3)getItemCount:獲取數據源總的條數。

(4)viewHolder:這是RecyclerView.ViewHolder的實現類,可用于初始化item布局中的子控件。需要注意的是,在這個類的構造方法中需要傳遞item布局的View給父類。

class FruitAdapter(val fruitList:List<Fruit>):RecyclerView.Adapter<FruitAdapter.ViewHolder>(){
    inner class ViewHolder(view: View):RecyclerView.ViewHolder(view){
        val fruitName:TextView=view.findViewById(R.id.fruitName)
        val fruitImage:ImageView=view.findViewById(R.id.fruitImage)
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view=LayoutInflater.from(parent.context).inflate(R.layout.fruit_item,parent,false)
        return ViewHolder(view)
    }
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val fruit=fruitList[position]
        holder.fruitImage.setImageResource(fruit.imageId)
        holder.fruitName.text=fruit.name
    }
    override fun getItemCount(): Int {
       return fruitList.size
    }
}

RecyclerView綁定數據適配器

class MainActivity : AppCompatActivity() {
    private val fruitList = ArrayList<Fruit>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //初始化控件
        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
        initFruits()
        //設置RecyclerView布局管理器
        val layoutManager = LinearLayoutManager(this)
        recyclerView.layoutManager = layoutManager
        //設置適配器
        val adapter = FruitAdapter(fruitList)
        recyclerView.adapter = adapter
    }
    private fun initFruits() {
        repeat(2) {
            fruitList.add(Fruit("Apple", R.drawable.apple_pic))
            fruitList.add(Fruit("Banana", R.drawable.banana_pic))
            fruitList.add(Fruit("Orange", R.drawable.orange_pic))
            fruitList.add(Fruit("Watermelon", R.drawable.watermelon_pic))
            fruitList.add(Fruit("Pear", R.drawable.pear_pic))
            fruitList.add(Fruit("Grape", R.drawable.grape_pic))
            fruitList.add(Fruit("Pineapple", R.drawable.pineapple_pic))
            fruitList.add(Fruit("Strawberry", R.drawable.strawberry_pic))
            fruitList.add(Fruit("Cherry", R.drawable.cherry_pic))
            fruitList.add(Fruit("Mango", R.drawable.mango_pic))
        }
    }
}

效果如圖:

3.實現橫向滾動

瀑布流布局和網格布局

橫向滾動

(1)對子布局進行修改

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="80dp"
    android:layout_height="wrap_content">
     <ImageView
         android:id="@+id/fruitImage"
         android:layout_width="40dp"
         android:layout_height="40dp"
         android:layout_gravity="center_horizontal"
         android:layout_marginTop="10dp"
         />
    <TextView
        android:id="@+id/fruitName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"/>
</LinearLayout>

(2)在MainActivity中加入一行代碼

layoutManager.orientation=LinearLayoutManager.HORIZONTAL//表示讓布局橫行排列

效果圖:

瀑布流布局

(1)對子布局進行修改

LinearLayout的寬度改為match_parent,因為瀑布流布局的寬度是根據布局的列數自動適配的,而不是一個固定值。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp">
     <ImageView
         android:id="@+id/fruitImage"
         android:layout_width="40dp"
         android:layout_height="40dp"
         android:layout_gravity="center_horizontal"
         android:layout_marginTop="10dp"
         />
    <TextView
        android:id="@+id/fruitName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:layout_marginTop="10dp"/>
</LinearLayout>

(2)在MainActivity中加入一行代碼

val layoutManager=StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL) 

效果圖:

網格布局

(1)在MainActivity中加入一行代碼

val layoutManager=GridLayoutManager(this,3)

效果圖:

4.RecyclerView的點擊事件

與ListView不同的是,RecyclerView并沒有提供類似于setOnItemClickListener()這樣的注冊監聽器,而是需要我們自己給子項具體的View去注冊點擊事件。

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view=LayoutInflater.from(parent.context).inflate(R.layout.fruit_item,parent,false)
        val viewHolder=ViewHolder(view)
        viewHolder.itemView.setOnClickListener {
            val position=viewHolder.bindingAdapterPosition
            val fruit=fruitList[position]
            Toast.makeText(parent.context,"你點擊了${fruit.name}",Toast.LENGTH_SHORT).show()
        }
        viewHolder.fruitImage.setOnClickListener{
            val position=viewHolder.bindingAdapterPosition
            val fruit=fruitList[position]
            Toast.makeText(parent.context,"你點擊了${fruit.name}的圖片",Toast.LENGTH_SHORT).show()
        }
        return viewHolder
    }

效果圖:

getAdapterPosition()方法被標記成了廢棄問題:

官方放棄getAdapterPosition()方法,換成了getbindingAdapter()和getAbsoluteAdapterPosition()方法,當使用recyclerView的監聽事件時,

getbindingAdapter():表示單個數據源的單獨位置。

getAbsoluteAdapterPosition():表示多個數據源的位置。

5.下拉刷新

1.SwipeRefreshLayout控件的介紹

SwipeRefreshLayout控件是谷歌公司提供的下拉刷新控件,具有使用簡單、靈活等特點。

SwipeRefreshLayout控件的方法有很大,這里只介紹常用的5個方法:

  • isRefreshing()

判斷當前的狀態是否是刷新狀態

  • setColorSchemeResources()

設置下拉進度條的顏色主題,參數為可變參數,并且為資源ID,可以用來設置多種不同的顏色,沒轉一圈就顯示一種顏色。

  • setOnRefreshListener()

設置監聽,需要重寫onRefresh()方法頂部下拉時會調用這個方法。在里面實現請求數據的邏輯,設置下拉進度條消失等。

  • setProgressBackgroundColorSchemeResource()

設置下拉進度條的背景顏色,默認為白色。

  • setRefreshing(boolean refreshing)

設置刷新狀態,true表示正在刷新,false表示取消刷新。

2.SwipeRefreshLayout控件的使用

添加依賴

implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'

在RecyclerView的外面嵌套一層SwipeRefreshLayout,這樣RecyclerView就擁有下拉刷新功能了。

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/swipeRefresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

首先調用swipeRefreshLayout的setColorSchemeResources()方法設置下拉刷新進度條的顏色,接著調用swipeRefreshLayout的setOnRefreshListener()方法來設置一個下拉刷新的監聽器,當觸發了下拉刷新事件時,就去網絡上請求最新的數據,然后再將這些數據展示出來。

    val swipeRefresh:SwipeRefreshLayout=findViewById(R.id.swipeRefresh)
        swipeRefresh.setColorSchemeResources(R.color.purple_200)
        swipeRefresh.setOnRefreshListener {
            thread {
                Thread.sleep(2000)
                runOnUiThread {
                    initFruits()
                    adapter.notifyDataSetChanged()
                    swipeRefresh.isRefreshing=false
                }
            }
        }

原文鏈接:https://blog.csdn.net/weixin_63357306/article/details/128052030

欄目分類
最近更新