Android kotlin RecyclerView遍歷json實(shí)現(xiàn)列表數(shù)據(jù)的案例
需求
效果圖如下 :
這個(gè)ui看起來(lái)簡(jiǎn)單, 其實(shí)要實(shí)現(xiàn)幾個(gè)功能點(diǎn)
1. json數(shù)據(jù)的遍歷
2. RecyclerView實(shí)現(xiàn)循環(huán)的列表
3. 每塊元素里的元素點(diǎn)擊 : 未選中的話, 首次點(diǎn)擊顯示"selected", 點(diǎn)擊"selected"則進(jìn)行下一步數(shù)據(jù)處理
4. 設(shè)置默認(rèn)的選擇的元素, 顯示selected
代碼
1. layout/item_region.xml 組件元素
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="50dp"> // 這里的高度需要注意, 就是每個(gè)需要遍歷的元素的高度, 千萬(wàn)要寫成不match_parent <LinearLayout android:id="@+id/item_region" android:layout_width="match_parent" android:layout_height="50dp" android:background="@drawable/bottom_border_white" android:gravity="center_vertical"> <TextView android:id="@+id/regionName" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_weight="2" android:text="China" android:textColor="@color/colorPrimary" android:textSize="16sp" /> <LinearLayout android:layout_width="0dp" android:layout_height="50dp" android:layout_weight="1" android:gravity="center_vertical" android:orientation="horizontal"> <TextView android:id="@+id/selectedBtn" android:layout_width="80dp" android:layout_height="wrap_content" android:text="Selected" android:textColor="@color/colorPrimary" android:textSize="16sp" android:visibility="invisible" /> <ImageView android:layout_width="10dp" android:layout_height="15dp" android:layout_marginLeft="15dp" android:src="@drawable/right_arrow" /> </LinearLayout> </LinearLayout> </LinearLayout>
2. activity_update_region.xml 主頁(yè)面
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/main_bg_color" android:orientation="vertical" > <LinearLayout android:id="@+id/updateArea_view" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="50dp" android:layout_marginLeft="20dp" android:layout_marginTop="40dp" android:gravity="center_vertical" android:text="All regions" android:textColor="@color/colorPrimary" android:textSize="16sp" android:textStyle="bold" /> <androidx.recyclerview.widget.RecyclerView android:id="@+id/regionListRecyclerView" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" /> </LinearLayout> </RelativeLayout>
3. Myactivity.kt
import kotlinx.android.synthetic.main.activity_update_area.regionListRecyclerView data class Country(val name: String, val code: Int, var selected: Boolean) /** * 設(shè)置頁(yè) */ class AreaupdateActivity : AppCompatActivity() { private lateinit var adapter: SimpleAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_update_area) // 讀取文件內(nèi)容 val jsonString = loadJsonFromAssets(this, "country.json") val gson = Gson() val countryName = "China" val countrys: List<Country> = gson.fromJson(jsonString, type) // 設(shè)置默認(rèn)的被選中的countryName selected if (countryName != null) { for (item in countrys) { if (item.name == countryName){ item.selected = true } } } regionListRecyclerView.layoutManager = LinearLayoutManager(this) adapter = SimpleAdapter(countrys) regionListRecyclerView.adapter = adapter // 元素的點(diǎn)擊事件 adapter.setOnItemClickListener(object : SimpleAdapter.OnItemClickListener { override fun onItemClick(position: Int, item: Country) { println("我點(diǎn)擊的$item") adapter.notifyItemChanged(position, item) // .indexOf(item) } }) } // 如果JSON文件位于assets目錄下, 這是處理非代碼資源文件(如文本、JSON等)的方式。通過(guò)AssetManager來(lái)訪問(wèn)這些文件。 fun loadJsonFromAssets(context: Context, fileName: String): String { val assetManager = context.assets val reader: BufferedReader var jsonString: String = "" try { reader = BufferedReader(InputStreamReader(assetManager.open(fileName))) jsonString = reader.use { it.readText() } } catch (e: Exception) { e.printStackTrace() // 處理異常情況 } return jsonString } // SimpleAdapter 適配器, 監(jiān)聽(tīng)列表元素 // 為了代碼的優(yōu)雅, 應(yīng)該單獨(dú)寫在Adapter里 class SimpleAdapter(private val countrys: List<Country>) : RecyclerView.Adapter<SimpleAdapter.SimpleViewHolder>() { private var selectedPosition = RecyclerView.NO_POSITION inner class SimpleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val regionName: TextView = itemView.findViewById(R.id.regionName) val selectedBtn: TextView = itemView.findViewById(R.id.selectedBtn) init { itemView.setOnClickListener { // 在這里處理點(diǎn)擊事件 onItemClickListener?.let { listener -> selectedPosition = adapterPosition notifyDataSetChanged() if (selectedPosition != RecyclerView.NO_POSITION) { listener.onItemClick(selectedPosition, getItem(selectedPosition)) } } } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SimpleViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_region, parent, false) return SimpleViewHolder(view) } interface OnItemClickListener { fun onItemClick(position: Int, item: Country) } private var onItemClickListener: OnItemClickListener? = null fun setOnItemClickListener(listener: OnItemClickListener) { onItemClickListener = listener } override fun onBindViewHolder(holder: SimpleViewHolder, position: Int) { val currentItem = getItem(position) holder.regionName.text = countrys[position].name // 點(diǎn)擊的顯示selected, 其他隱藏 holder.selectedBtn.visibility = if (position == selectedPosition) View.VISIBLE else View.INVISIBLE // 初始化數(shù)據(jù) currentItem.selected為true的顯示 // 點(diǎn)擊的時(shí)候 原currentItem.selected為true的變?yōu)閒alse, 點(diǎn)擊的這個(gè)元素selected顯示 if (currentItem.selected) { currentItem.selected = !currentItem.selected holder.selectedBtn.visibility = View.VISIBLE println("我顯示著") } // 點(diǎn)擊selected holder.selectedBtn.setOnClickListener { var countryStr = currentItem.name CoroutineScope(Dispatchers.IO).launch { updateInfo(countryStr) // 更新用戶數(shù)據(jù)(自定義function) } } } override fun getItemCount(): Int = countrys.size fun getItem(position: Int): Country { return countrys[position] } } }
4. assets/country.json (示例)
[{ "selected": false, "country_id": 100006, "country_code": 244, "name": "Angola", "country_name_cn": "安哥拉", "ab": "AO" }, { "selected": false, "country_id": 100008, "country_code": 355, "name": "Albania", "country_name_cn": "阿爾巴尼亞", "ab": "AL" }]
完成!
其中難點(diǎn)是上述第3條功能, 因?yàn)樾枰僮鱥tem里的元素, 相比item, 里面的元素更難獲取和操作, 其次是selected的初始化和兩次點(diǎn)擊的操作, 還有點(diǎn)擊時(shí)其他selected的隱藏
對(duì)比uniapp的感受 :
① 組件的適配器和數(shù)據(jù)監(jiān)聽(tīng)交給開(kāi)發(fā)者去寫, 此為難度一, 而uniapp僅需一個(gè)v-for完成遍歷
② 點(diǎn)擊事件的處理, Android需要開(kāi)發(fā)者自己找到選中的元素及其子元素, 再對(duì)其及其兄弟元素操作, 有點(diǎn)類似jquery, 操作dom節(jié)點(diǎn), 而非vue一樣操作數(shù)據(jù), 邏輯性會(huì)更強(qiáng)一些
到此這篇關(guān)于Android kotlin RecyclerView遍歷json實(shí)現(xiàn)列表數(shù)據(jù)的文章就介紹到這了,更多相關(guān)Android kotlin RecyclerView列表數(shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Android使用RecyclerView實(shí)現(xiàn)列表數(shù)據(jù)選擇操作
- kotlin android extensions 插件實(shí)現(xiàn)示例詳解
- 一文讀懂Android?Kotlin的數(shù)據(jù)流
- Android使用ViewBinding的詳細(xì)步驟(Kotlin簡(jiǎn)易版)
- Android入門之使用RecyclerView完美實(shí)現(xiàn)瀑布流界面詳解
- Android studio listview實(shí)現(xiàn)列表數(shù)據(jù)顯示 數(shù)據(jù)循環(huán)顯示效果
- Android列表組件ListView使用詳解之動(dòng)態(tài)加載或修改列表數(shù)據(jù)
相關(guān)文章
android 6.0下webview的定位權(quán)限設(shè)置方法
今天小編就為大家分享一篇android 6.0下webview的定位權(quán)限設(shè)置方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-07-07Android?hid發(fā)送apdu格式數(shù)據(jù)示例詳解
這篇文章主要介紹了Android?hid發(fā)送apdu格式數(shù)據(jù),在?Android?中,如果你想通過(guò)?HID(Human?Interface?Device)發(fā)送?APDU?格式的數(shù)據(jù),通常會(huì)涉及?USB?HID?設(shè)備或藍(lán)牙?HID?設(shè)備,本文給大家講解的非常詳細(xì),需要的朋友可以參考下2023-08-08Android Scroll實(shí)現(xiàn)彈性滑動(dòng)_列表下拉彈性滑動(dòng)的示例代碼
下面小編就為大家分享一篇Android Scroll實(shí)現(xiàn)彈性滑動(dòng)_列表下拉彈性滑動(dòng)的示例代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-01-01Android網(wǎng)絡(luò)請(qǐng)求-sign參數(shù)的設(shè)置方式
這篇文章主要介紹了Android網(wǎng)絡(luò)請(qǐng)求-sign參數(shù)的設(shè)置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03android教程之使用asynctask在后臺(tái)運(yùn)行耗時(shí)任務(wù)
AsyncTask用在需要在ui線程中調(diào)用、在背景線程中執(zhí)行耗時(shí)任務(wù)、并且在ui線程中返回結(jié)果的場(chǎng)合。下面就是一個(gè)在背景中運(yùn)行的AsyncTask的實(shí)現(xiàn)DownloadDBTask2014-02-02用Kotlin實(shí)現(xiàn)Android點(diǎn)擊事件的方法
本篇文章主要介紹了用Kotlin實(shí)現(xiàn)Android點(diǎn)擊事件的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06Android之FanLayout制作圓弧滑動(dòng)效果
這篇文章主要介紹了Android之FanLayout制作圓弧滑動(dòng)效果,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-08-08