I have the following:
- Main Activity with RecyclerView which is filled from Array List
- Adapter (of course)
- Another Activity where a new item should be created, added to RecyclerView on Main Activity and then be closed
The main question is, how can I add an item to RecyclerView from another Activity?
MainActivity Code
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val items = arrayListOf<CustomData>()
items.add(CustomData("Name", R.drawable.icon, 50, "Weekly", "Monday", 1, 50))
button.setOnClickListener {
val intent = Intent(this, NewItem::class.java)
startActivity(intent)
}
itemsListView.apply {
layoutManager = LinearLayoutManager(this@MainActivity)
adapter = ItemsAdapter(items)
}
}
Adapter Code
class ItemsAdapter(private val items: ArrayList<CustomData>) :
RecyclerView.Adapter<ItemsAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.wish_row, parent, false)
val holder = ViewHolder(view)
view.setOnClickListener {
val intent = Intent(parent.context, ItemView::class.java)
intent.putExtra("Name", items[holder.adapterPosition].name)
intent.putExtra("Price", items[holder.adapterPosition].price)
intent.putExtra("Icon", items[holder.adapterPosition].image)
parent.context.startActivity(intent)
}
return holder
}
override fun getItemCount() = items.size
override fun onBindViewHolder(holder: ItemsAdapter.ViewHolder, position: Int) {
holder.name.text = items[position].name
holder.price.text = items[position].price.toString()
holder.image.setImageDrawable(holder.image.context.getDrawable(items[position].image))
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val image: ImageView = itemView.findViewById(R.id.imageView)
val name: TextView = itemView.findViewById(R.id.textView)
val price: TextView = itemView.findViewById(R.id.textView2)
}
}
Another Activity from which I want to add item to Recyclerview
class NewItem : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.new_item_activity)
val items = arrayListOf<CustomData>()
items.add(CustomData("Name2", R.drawable.icon, 50, "Weekly", "Monday", 2, 50))
newItemButton.setOnClickListener {
itemsListView.layoutManager = LinearLayoutManager(this)
itemsListView.adapter = itemsAdapter(items)
finish()
}
}
}