Android入門教程之RecyclerView的具體使用詳解
RecyclerView 的基本用法
和我們之前學習的控件不一樣,RecyclerView 屬於新增控件,所以我們需要在項目的 build.gradle 中添加 RecyclerView 庫的依賴,才能使用該控件
dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" implementation 'androidx.core:core-ktx:1.2.0' implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'com.google.android.material:material:1.1.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation 'androidx.recyclerview:recyclerview:1.1.0' testImplementation 'junit:junit:4.+' androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' }
修改 activity_main.xml 中的代碼,如下所示
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" 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" /> </LinearLayout>
這裡我們想要使用 RecyclerView 實現瞭 ListView 一樣的效果,準備一個適配器,新建 FruitAdapter 類,讓這個適配器繼承 RecyclerView.Adapter,並將泛型指定為 FruitAdapter.ViewHolder,其中 ViewHolder 是我們在 FruitAdapter 中定義的一個內部類
class FruitAdapter(val fruitList: List<Fruit>) : RecyclerView.Adapter<FruitAdapter.ViewHolder>() { inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val fruitImage: ImageView = view.findViewById(R.id.fruitImage) val fruitName: TextView = view.findViewById(R.id.fruitName) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FruitAdapter.ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.fruit_item, parent, false) return ViewHolder(view) } override fun getItemCount() = fruitList.size override fun onBindViewHolder(holder: FruitAdapter.ViewHolder, position: Int) { val fruit = fruitList[position] holder.fruitImage.setImageResource(fruit.imageId) holder.fruitName.text = fruit.name } }
首先,我們定義一個內部類 ViewHolder,繼承自 RecyclerView.ViewHolder,然後 ViewHolder 的主構造函數中傳入一個 View 參數,這個參數通常是 RecyclerView 子項的最外層佈局,然後我們就可以通過 findViewById() 方法來獲取佈局中的 ImageView 和 TextView 實例瞭
FruitAdapter 繼承自 RecyclerView.Adapter,那麼就必須重寫 onCreateViewHolder()、onBindViewHolder()、getItemCount() 這三個方法:
- onCreateViewHolder() 方法用於創建 ViewHolder 實例
- onBindViewHolder() 方法用於對 RecyclerView 子項的數據進行賦值
- getItemCount() 方法告訴 RecyclerView 一共有多少個子項,直接返回數據源的長度
修改 MainActivity 中的代碼,開始使用 RecyclerView
class MainActivity : AppCompatActivity() { private val fruitList = ArrayList<Fruit>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initFruits() 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)) } } }
在 onCreate() 方法中先創建一個 LinearLayoutManager 對象,並設置到 RecyclerView 中,用於指定 RecyclerView 的佈局方式。然後再創建 FruitAdapter 的實例,調用 RecyclerView 的 setAdapter() 方法完成適配器設置
橫向滾動
如果我們要實現橫向滾動的話,要先對 fruit_item 的佈局進行修改,把裡面的元素改成垂直排列
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="80dp" android:layout_height="wrap_content" tools:ignore="UseCompoundDrawables"> <ImageView android:id="@+id/fruitImage" android:layout_width="40dp" android:layout_height="40dp" android:layout_gravity="center_vertical" android:layout_marginLeft="10dp" tools:ignore="ContentDescription,RtlHardcoded" /> <TextView android:id="@+id/fruitName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginLeft="10dp" tools:ignore="RtlHardcoded" /> </LinearLayout>
接下來修改 MainActivity 中的代碼
class MainActivity : AppCompatActivity() { private val fruitList = ArrayList<Fruit>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initFruits() val layoutManager = LinearLayoutManager(this) layoutManager.orientation = LinearLayoutManager.HORIZONTAL recyclerView.layoutManager = layoutManager val adapter = FruitAdapter(fruitList) recyclerView.adapter = adapter } ... }
除瞭橫向滾動,RecyclerView 還能實現瀑佈流和網格佈局
RecyclerView 點擊事件
不同於 ListView,RecyclerView 並沒有提供類似於 setOnItemClickListener() 這樣的註冊監聽器方法,而是需要我們自己給子項具體的 View 註冊點擊事件
修改 FruitAdapter 中的代碼
class FruitAdapter(val fruitList: List<Fruit>) : RecyclerView.Adapter<FruitAdapter.ViewHolder>() { inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val fruitImage: ImageView = view.findViewById(R.id.fruitImage) val fruitName: TextView = view.findViewById(R.id.fruitName) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FruitAdapter.ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.fruit_item, parent, false) val viewHolder = ViewHolder(view) viewHolder.itemView.setOnClickListener { val position = viewHolder.adapterPosition Log.d("FruitAdapter", position.toString()) val fruit = fruitList[position] Toast.makeText(parent.context, "you clicked view ${fruit.name}", Toast.LENGTH_SHORT).show() } viewHolder.fruitImage.setOnClickListener { val position = viewHolder.adapterPosition Log.d("FruitAdapter", position.toString()) val fruit = fruitList[position] Toast.makeText(parent.context, "you clicked image ${fruit.name}", Toast.LENGTH_SHORT).show() } return viewHolder } override fun getItemCount() = fruitList.size override fun onBindViewHolder(holder: FruitAdapter.ViewHolder, position: Int) { val fruit = fruitList[position] holder.fruitImage.setImageResource(fruit.imageId) holder.fruitName.text = fruit.name } }
到此這篇關於Android入門教程之RecyclerView的具體使用詳解的文章就介紹到這瞭,更多相關Android RecyclerView內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- Android入門教程之ListView的具體使用詳解
- Android滾動菜單ListView實例詳解
- RecyclerView實現橫向滾動效果
- RecyclerView使用payload實現局部刷新
- android RecyclerView添加footerview詳解