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 指定給recycleviewrecycleview_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)
}