iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 5
0

ListView在APP上應該是最常見的布局方式。
先上個圖

在RecycleView中,要呈現listView的樣式,需要用到LinearLayoutManager來實作。

不囉唆 先上Activity

class ListViewActivity : AppCompatActivity() {
    lateinit var linearLayoutManager: LinearLayoutManager
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        linearLayoutManager = LinearLayoutManager(this)
        recycleview_main.layoutManager= linearLayoutManager
        
        val adapter = RVListViewAdapter(this, SwitchData.defaultList)
        recycleview_main.adapter = adapter

    }
}

有時候沒有畫面就是忘記要把linearLayoutManager 指定給recycleview
recycleview_main.layoutManager= linearLayoutManager

RecycleViewAdapter

class RVListViewAdapter(
    private val context: Context,
    private val dataList: MutableList<SwitchData>
) :
    RecyclerView.Adapter<RVListViewAdapter.ViewHolder>() {
    lateinit var mContext: Context

    init {
        mContext = context
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        var view = LayoutInflater.from(parent.context).inflate(R.layout.recycleview_listview_layout, parent, false)
        return ViewHolder(view, viewType)
    }
    override fun getItemCount(): Int {
        return dataList.size
    }
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = dataList[position]
        holder?.bindModel(item)
    }
    inner class ViewHolder(itemView: View, var viewType: Int) : RecyclerView.ViewHolder(itemView) {
        var nameTextView: TextView? = null
        var likeTextView: TextView? = null
        var commentTextView: TextView? = null

        fun bindModel(item: SwitchData) {
            var imageView: ImageView? = null
            imageView = itemView.findViewById(R.id.iv_Large)
            nameTextView = itemView.findViewById(R.id.tv_nameLarge)
            likeTextView = itemView.findViewById(R.id.tv_like)
            commentTextView = itemView.findViewById(R.id.tv_comment)

            Glide.with(mContext).load(item.image).into(imageView!!)
            nameTextView?.setText(item.name)
            likeTextView?.setText("Likes: ${item.like}")
            commentTextView?.setText("comments: ${item.comment}")

        }

    }
}

這邊推薦用ViewHolder下宣告bind函式,然後在onBindViewHolder中指定項目

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val item = dataList[position]
    holder?.bindModel(item)
}

上一篇
利用Glide製作圓形圖片 前景加背景一次滿足 LayerDrawable
下一篇
RecycleView GridView布局
系列文
跟Kotlin一起來聊Android元件 或許還有應用,或許還有一些資訊雜談30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言