重庆专业的网站建设,做网站赚钱一般做什么,大型网站开发项目书籍,百度小程序开发工具Kotlin 案例1. recyclerView#xff1a;显示列表
这里#xff0c;我们将通过几个案例来介绍如何使用recyclerView。RecyclerView 是 ListView 的高级版本。 当我们有很长的项目列表需要显示的时候#xff0c;我们就可以使用 RecyclerView。 它具有重用其视图的能力。 在 Re…Kotlin 案例1. recyclerView显示列表
这里我们将通过几个案例来介绍如何使用recyclerView。RecyclerView 是 ListView 的高级版本。 当我们有很长的项目列表需要显示的时候我们就可以使用 RecyclerView。 它具有重用其视图的能力。 在 RecyclerView 中当 View 离开屏幕或对用户不可见时它不会被销毁这些视图会被重用。 此功能有助于降低功耗并为应用程序提供更高的响应能力。
IDE: Android StudioLanguage: KotlinKey words: Determinate ProgressBar, Indeterminate ProgressBarAPI tested: 32完整代码下载地址: 文章目录Kotlin 案例1. recyclerView显示列表1 结果2 总结3 准备4 activity_main.xml5 item_main.xml6 ItemClickListener.kt7 MainAdapter.kt8 MainActivity.kt1 结果 这个案例本身比较简单。但通过这个案例我们可以用最直白地方式解释 RecyclerView 的使用方式。APP 启动后界面会显示一个地址列表当我们点击列表中的任何一项后系统会弹出 Toast 提示Position: X || Value: Address X。
2 总结
通过这个案例我们可以先进行一个简单的总结如果我们要建一个 RecyclerView我们起码需要哪些东西。
需要显示列表的xml界面我们需要有一个 androidx.recyclerview.widget.RecyclerView / 模块一个列表有一项项item组成我们需要有一个xml文件去描述这个item。在这个例子中对应的是item_main.xmlRecyclerView 最起码需要一个 adaptor 类它包含了三个函数 onCreateViewHolder()此函数新建View以返回ViewHolderonBindViewHolder()该函数用于将列表项绑定到我们的各个部件如 TextView、ImageView 等。getItemCount()它返回列表中存在的项目的计数。 当然最后我们需要在显示列表的xml界面调用上面这个 adaptor 类行程列表。
3 准备
我们在android studio中新建一个项目如下为我的AndroidManifest.xml, build_gradle (Project)以及build_gradle (app)的代码。
AndroidManifest.xml
?xml version1.0 encodingutf-8?
manifest xmlns:androidhttp://schemas.android.com/apk/res/androidxmlns:toolshttp://schemas.android.com/toolspackagecom.example.RecyclerViewAddressListExapplicationandroid:allowBackuptrueandroid:dataExtractionRulesxml/data_extraction_rulesandroid:fullBackupContentxml/backup_rulesandroid:iconmipmap/ic_launcherandroid:labelstring/app_nameandroid:roundIconmipmap/ic_launcher_roundandroid:supportsRtltrueandroid:themestyle/Theme.RecyclerViewAddressListExtools:targetApi31activityandroid:name.MainActivityandroid:exportedtrueintent-filteraction android:nameandroid.intent.action.MAIN /category android:nameandroid.intent.category.LAUNCHER //intent-filter/activity/application/manifest注意我这里给项目命名为 RecyclerViewAddressListEx。
build_gradle (Project)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {id com.android.application version 7.2.1 apply falseid com.android.library version 7.2.1 apply falseid org.jetbrains.kotlin.android version 1.6.10 apply false
}task clean(type: Delete) {delete rootProject.buildDir
}build_gradle (app)
plugins {id com.android.applicationid org.jetbrains.kotlin.android
}android {compileSdk 32defaultConfig {applicationId com.example.recyclerviewexampleminSdk 26targetSdk 32versionCode 1versionName 1.0testInstrumentationRunner androidx.test.runner.AndroidJUnitRunner}buildTypes {release {minifyEnabled falseproguardFiles getDefaultProguardFile(proguard-android-optimize.txt), proguard-rules.pro}}compileOptions {sourceCompatibility JavaVersion.VERSION_1_8targetCompatibility JavaVersion.VERSION_1_8}kotlinOptions {jvmTarget 1.8}
}dependencies {implementation androidx.core:core-ktx:1.8.0implementation androidx.appcompat:appcompat:1.4.2implementation com.google.android.material:material:1.6.1implementation androidx.constraintlayout:constraintlayout:2.1.4testImplementation junit:junit:4.13.2androidTestImplementation androidx.test.ext:junit:1.1.3androidTestImplementation androidx.test.espresso:espresso-core:3.4.0
}4 activity_main.xml
我们将 RecyclerView 添加到 activity_main.xml 试图中。
?xml version1.0 encodingutf-8?
androidx.constraintlayout.widget.ConstraintLayout xmlns:androidhttp://schemas.android.com/apk/res/androidxmlns:apphttp://schemas.android.com/apk/res-autoxmlns:toolshttp://schemas.android.com/toolsandroid:layout_widthmatch_parentandroid:layout_heightmatch_parenttools:context.MainActivityandroidx.recyclerview.widget.RecyclerViewandroid:layout_widthmatch_parentandroid:layout_heightmatch_parentandroid:idid/recycler_viewtools:listitemlayout/item_main//androidx.constraintlayout.widget.ConstraintLayout注意上面一行tools:listitemlayout/item_main也就是说对于 RecyclerView 它是由一行行的 item 构成的这个 item 的试图就在 item_main.xml 中填写。
5 item_main.xml
新建 item_main.xml 右键layout New Layout Resource File
?xml version1.0 encodingutf-8?
androidx.cardview.widget.CardViewxmlns:androidhttp://schemas.android.com/apk/res/androidandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentxmlns:apphttp://schemas.android.com/apk/res-autoandroid:idid/card_viewandroid:layout_margin4dpapp:cardCornerRadius8dpTextViewandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentandroid:idid/text_Viewandroid:textSize20spandroid:padding20dpandroid:gravitycenter//androidx.cardview.widget.CardView这里每一个 item 由 TextView 构成。我们也可以添加 ImageView 或者其他元素。
6 ItemClickListener.kt
该文件将保存我们要在 RecyclerView 中显示的每个项目的信息也就是说我们点了这个按钮之后会发生什么。
interface ItemClickListener {fun onClick(position: Int, value: String?)
}这里我们只是定义了一个接口然后定义了一个 onClick 函数。具体的实现在 MainActivity.kt 中。
7 MainAdapter.kt
这里我们需要创建一个 adaptor 类此类包含一些与 RecyclerView 一起使用的重要功能如下所示
onCreateViewHolder()此函数新建View以返回ViewHolderonBindViewHolder()该函数用于将列表项绑定到我们的各个部件如 TextView、ImageView 等。getItemCount()它返回列表中存在的项目的计数。
MainAdapter.kt 代码如下
package com.example.recyclerviewaddresslisteximport android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerViewclass MainAdapter // create constructor(// initialize variablesvar arrayList: ArrayListString, var itemClickListener: ItemClickListener
) :RecyclerView.AdapterMainAdapter.ViewHolder() {var selectedPosition -1// create new viewsoverride fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {// inflates the card_view_design view// that is used to hold list itemval view: View LayoutInflater.from(parent.context).inflate(R.layout.item_main, parent, false)// return holderreturn ViewHolder(view)}// binds the list items to a viewoverride fun onBindViewHolder(holder: ViewHolder, position: Int) {// set value on text viewholder.textView.text arrayList[position]holder.itemView.setOnClickListener(object : View.OnClickListener {override fun onClick(v: View?) {// get adapter positionval position holder.adapterPosition// call listeneritemClickListener.onClick(position, arrayList[position])// update positionselectedPosition position// notifynotifyDataSetChanged()}})// check conditionsif (selectedPosition position) {// When current position is equal// to selected position// set black background colorholder.cardView.setCardBackgroundColor(Color.parseColor(#000000))// set white text colorholder.textView.setTextColor(Color.parseColor(#FFFFFF))} else {// when current position is different// set white backgroundholder.cardView.setCardBackgroundColor(Color.parseColor(#FFFFFF))// set black text colorholder.textView.setTextColor(Color.parseColor(#000000))}}// return the number of the items in the listoverride fun getItemCount(): Int {// return array list sizereturn arrayList.size}// Holds the views for adding it to image and textinner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {// initialize variablevar cardView: CardViewvar textView: TextViewinit {// assign variablecardView itemView.findViewById(R.id.card_view)textView itemView.findViewById(R.id.text_View)}}
}8 MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerViewclass MainActivity : AppCompatActivity() {// initialize variableprivate lateinit var recyclerView: RecyclerViewvar arrayList: ArrayListString ArrayList()var adapter: MainAdapter? nullvar itemClickListener: ItemClickListener? nulloverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)// getting the recyclerview by its idrecyclerViewfindViewById(R.id.recycler_view);// getting the recyclerview by its id// use for loop// use for loopfor (i in 0..14) {// add values in array listarrayList.add(Address $i)}// Initialize listener// Initialize listeneritemClickListener object : ItemClickListener {override fun onClick(position: Int, value: String?) {// Display toastToast.makeText(applicationContext, Position : position || Value : value, Toast.LENGTH_SHORT).show()}}// this creates a vertinullcal layout ManagerrecyclerView.layoutManager LinearLayoutManager(this)// Initialize adapteradapter MainAdapter(arrayList, itemClickListener as ItemClickListener)// set adapterrecyclerView.adapter adapter}
}上面代码中的 arrayList 其实就是最终呈现在 RecyclerView 视图中的 TextView 的集合。
for (i in 0..14) {// add values in array listarrayList.add(Address $i)
}另外这里也定义了按下按钮后的反馈
// Initialize listener
itemClickListener object : ItemClickListener {override fun onClick(position: Int, value: String?) {// Display toastToast.makeText(applicationContext, Position : position || Value : value, Toast.LENGTH_SHORT).show()}
}最后我们设置adaptor
// Initialize adapter
adapter MainAdapter(arrayList, itemClickListener as ItemClickListener)
// set adapter
recyclerView.adapter adapter