I based my code on an example I found that uses Android Architecture Components and data binding. This is a new way for me, and the way it is coded makes it hard to properly open a new activity with the information of the post that was clicked.
This is the adapter of the posts
class PostListAdapter : RecyclerView.Adapter<PostListAdapter.ViewHolder>() {
private lateinit var posts: List<Post>
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostListAdapter.ViewHolder {
val binding: ItemPostBinding = DataBindingUtil.inflate(
LayoutInflater.from(parent.context),
R.layout.item_post,
parent, false
)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: PostListAdapter.ViewHolder, position: Int) {
holder.bind(posts[position])
}
override fun getItemCount(): Int {
return if (::posts.isInitialized) posts.size else 0
}
fun updatePostList(posts: List<Post>) {
this.posts = posts
notifyDataSetChanged()
}
inner class ViewHolder(private val binding: ItemPostBinding) : RecyclerView.ViewHolder(binding.root) {
private val viewModel = PostViewModel()
fun bind(post: Post) {
viewModel.bind(post)
binding.viewModel = viewModel
}
}
}
The bind
method comes from within the view model class:
class PostViewModel : BaseViewModel() {
private val image = MutableLiveData<String>()
private val title = MutableLiveData<String>()
private val body = MutableLiveData<String>()
fun bind(post: Post) {
image.value = post.image
title.value = post.title
body.value = post.body
}
fun getImage(): MutableLiveData<String> {
return image
}
fun getTitle(): MutableLiveData<String> {
return title
}
fun getBody(): MutableLiveData<String> {
return body
}
fun onClickPost() {
// Initialize new activity from here, perhaps?
}
}
And in the layout XML, setting on an onClick
attribute
android:onClick="@{() -> viewModel.onClickPost()}"
pointing to this onClickPost
method does work but I can't initialize the Intent
from there. I tried many ways to acquire the MainActivitiy
's context, without success, such as
val intent = Intent(MainActivity::getApplicationContext, PostDetailActivity::class.java)
But it displays an error on time.