iT邦幫忙

2021 iThome 鐵人賽

DAY 6
0
自我挑戰組

Android kotlin &MVVM系列 第 6

Android學習筆記06

  • 分享至 

  • xImage
  •  

kotlin+mvvm+databinding+recyclerview
今天在跟朋友討論程式碼的時候,他點出我用databing是可以不需要listener的,我稍微修改了一些前兩天的程式碼,也把前兩天的code整合起來
在結合code之前,我實作了一個viewmodelFactor,是用擴展的方式實作

class ViewModelFactory(application: Application) : ViewModelProvider.AndroidViewModelFactory(application)

fun <T : ViewModel> ViewModelStoreOwner.initViewModel(application: Application, viewModel: Class<T>): T = ViewModelProvider(this,
    ViewModelFactory(application = application)).get(viewModel) 

這邊要繼承AndroidViewModel因為可以引入application
再來是修改過後的activity,adapter,viewmodel
首先是activity

class Activity:AppCompatActivity() {
    lateinit var binding: ActivityMainBinding

    private val mViewModel by lazy {
        initViewModel(application, ViewModel::class.java)
    }

    private val mAdapter by lazy {
        Adapter<Post>(R.layout.item_view,mViewModel)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        binding.recyclerView.adapter = mAdapter

        mViewModel.data.observe(this, Observer { post ->
            mAdapter.updateData(post)
        })
        mViewModel.fetchData()
    }
}

adapter

class Adapter<T>(
    @LayoutRes val resource: Int,
    val viewmodel:ViewModel
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private val data: List<T>
        get() = _data.toList()
    private val _data: MutableList<T> = mutableListOf()

    fun updateData(list: ArrayList<T>){
        _data.clear()
        _data.addAll(list)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val layoutInflater = LayoutInflater.from(parent.context)
        val binding = DataBindingUtil.inflate<ViewDataBinding>(layoutInflater, resource, parent,false)
        return MyViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return data.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is Adapter<*>.MyViewHolder){
            val item = data[position]
            if (item != null)
                holder.setupData(item)
        }

    }

    inner class MyViewHolder( var binding: ViewDataBinding):RecyclerView.ViewHolder(binding.root){
        fun setupData(post: Any){
            binding.setVariable(BR.Post, post)
            binding.setVariable(BR.viewmodel,viewmodel)
        }
    }

}

viewmodel

![https://ithelp.ithome.com.tw/upload/images/20210915/20141791zjHci8JfER.jpg](https://ithelp.ithome.com.tw/upload/images/20210915/20141791zjHci8JfER.jpg)```

上一篇
Android學習筆記05
下一篇
Android學習筆記07
系列文
Android kotlin &MVVM30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言