Recycler View也是清單元件的一種,會依照傳入的Layout,自動對項目進行調整以符合螢幕大小
建立一個資料類別儲存資料
data class Account(
val title: String,
val amount:Int
)
建立一個ArrayList,做為資料來源
private var accounts = ArrayList<Account>()
class adapter (private val accounts: ArrayList<Account>,private val context: Context):RecyclerView.Adapter<adapter.ViewHolder>()
{
//實作ViewHolder緩存View
class ViewHolder(v: View): RecyclerView.ViewHolder(v)
{
//取得元件
val tv_title = v.findViewById<TextView>(R.id.tv_title)
val tv_amount = v.findViewById<TextView>(R.id.tv_amount)
}
//連接畫面
override fun onCreateViewHolder(viewGroup: ViewGroup, position: Int): ViewHolder
{
val v = LayoutInflater.from(viewGroup.context).inflate(R.layout.item,viewGroup,false)
return ViewHolder(v)
}
//回傳資料數量
override fun getItemCount() = accounts.size
//將資料顯示到元件中
override fun onBindViewHolder(holder: ViewHolder, position: Int)
{
holder.tv_title.text = accounts[position].title
holder.tv_amount.text = "${accounts[position].amount}"
}
}
在MainActivity中連接RecyclerView和Adapter
var adapter: adapter
//設定為垂直顯示
val linearLayoutManager = LinearLayoutManager(this)
linearLayoutManager.orientation = RecyclerView.VERTICAL
recyclerView.layoutManager = linearLayoutManager
adapter = adapter(accounts)
recyclerView.adapter = adapter
將EditText中的內容新增到資料列表中
button.setOnClickListener {
if(!(ed_title.length() < 1 && ed_amount.length() < 1)){
accounts.add(Account("${ed_title.text}",ed_amount.text.toString().toInt()))
//更新列表
adapter.notifyDataSetChanged()
//將每一筆的金額加總並顯示
var total = 0
for(i in 0 until accounts.size){
total += accounts[i].amount
}
tv_total.text = "總金額:$total"
}
}