Day 8 | 比较漂亮的清单-客制化Adapter

Adapter客制化

当需要图文并茂时,就需要客制化Adapter。

  1. 建立资料

    data class Item{
    		val photo: Int,
    		val name: String
    }
    //宣告一个ArrayList,内部为自行设计的Item类别
    val item = ArrayList<Item>()
    //用回圈产生资料,并放入ArrayList中
    for(i in 0 until 10)
    		item.add(Item(i, "水果${i+1}"))
    
    
  2. 设计项目的Layout

    图片用ImageView、文字用TextView

  3. 建立客制化Adapter

    class MyAdapter(context: Context, private val data: ArrayList<Item>) :
    		ArrayAdapter<Item>(context, R. layout.adapter _horizontal, data) {
    		//回传资料集合的数量
    		override fun getCount() = data.size
    		//回传指定位置的资料
    		override fun getItem(position: Int) = data[position]
    		//回传指定位置的资料识别标铁
    		override fun getItemId(position: Int) = OL
    		//回傅指定位置的项目画面
    		override fun getView(position: Int, convertView: View?,parent: ViewGroup) : View {
    				//依据adapter_horizontal建立画面
    				val view = View.inflate(parent.context, R.layout.adapter_horizontal, null)
    				//依据position取得对应的资料内容
    				val item = getItem(position) ?: return view
    				//将资料指派给元件呈现
    				val img_photo = view.findViewById<ImageView>(R.id.img_photo)
    				val tv_name = view.findViewById<TextView>(R.id.tv_name)
    				img_photo.setImageResource (item.photo)
    				tv_name.text = item.name
    				//回传此项目的画面
    				return view
    		}
    }
    
    • getCount()会回传资料数量,通常放入资料集合的总数量
    • getItem(position: Int)传入特定位置,回传此位置的的资料内容
    • getItemID(position: Int)传入特定位置,回传此位置资料的识别标签,识别标签具有唯一性
    • getView(position: Int, convertView: View?,parent: ViewGroup)会回传特定位置的项目画面,使用者要先初始化画面,将项目编号(position)传入getItem,从资料集合中取得此项目编号的资料,并把资料指派给元件呈现,最後回传此项目的画面给清单元件显示。

<<:  第三天:以软件包安装 TeamCity

>>:  Day 6 : Github issue与project

Day 04 HTML/JavaScript Attribute vs Property

Attribute vs Property attribute:属性在 HTML 会被称为 attr...

[Flutter ] Django 为资料库,以 FutureBuilder + http 抓取

Free fake API 为资料库,以 FutureBuilder + http 抓取 为Flut...

Day 12 均衡思考赚钱与不被花钱

依现况而言企业在强大的个资隐私规范之下,如何符合规范又不被在不知情况之下被罚又不知所云,在个资自主当...

[Day 28 - 小试身手] Todolist with React (3)

在上一章Todolist with React (2),完成所有样式设定後,现在就让我们在 Rea...

Day27 语法改革!零基础新手也能读懂的JS - JS30-01 Drum Kit

JS30官网 先到上方官网下载试题,今天就来试试看JS30第一天吧!主要是来讲解作者是怎麽撰写的! ...