Kotlin: Show AlertDialog when RecycleView item clicked - kotlin

Now I'm studying to show AlertDialog when RecyclerView item clicked.
However, I don't know how to set the adapter for click listener.
Could you give me a tip?
Firstly, I tried to put the AlertDialog in this Main Activity.
Is this right position?
MainActivity
class MainActivity : AppCompatActivity() {
private val foodList = listOf(
FoodModel("Noodle", 2),
FoodModel("Cake", 3),
FoodModel("Pizza", 4),
FoodModel("Stake", 5),
FoodModel("Chicken", 4)
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val adapter = FoodDataAdapter(foodList)
adapter.notifyDataSetChanged()
foodListView.adapter = adapter
foodListView.layoutManager = LinearLayoutManager(this)
fun onItemClick(item: FoodModel, position: Int) {
val dialog = AlertDialog.Builder(this)
dialog.setTitle("Item deletion")
dialog.setMessage("Do you want to delete this item?")
dialog.setPositiveButton("Yes", DialogInterface.OnClickListener { _, _ ->
})
dialog.setNegativeButton("No", DialogInterface.OnClickListener { _, _ ->
})
dialog.setNeutralButton("Cancel", DialogInterface.OnClickListener { _, _ ->
})
dialog.show()
}
}
}
This is the Adapter.
class FoodDataAdapter(val list: List<FoodModel>):RecyclerView.Adapter<FoodDataViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FoodDataViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_food,parent,false)
return FoodDataViewHolder(view)
}
override fun getItemCount(): Int {
return list.count()
}
override fun onBindViewHolder(holder: FoodDataViewHolder, position: Int) {
holder.containerView.nameText.text=list[position].name
holder.containerView.priceText.text="${list[position].price}dollar"
}
}
View holder
class FoodDataViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView),LayoutContainer

I edited your code. MainActivity:
class MainActivity : AppCompatActivity(), FoodDataAdapter.OnItemClickListener {
var foodList = ArrayList<FoodModel>()
lateinit var adapter : FoodDataAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
foodlist.add(FoodModel("Noodle", 2))
foodlist.add(FoodModel("Cake", 3))
foodlist.add(FoodModel("Pizza", 4))
foodlist.add(FoodModel("Stake", 5))
foodlist.add(FoodModel("Chicken", 4))
adapter = FoodDataAdapter(foodList, this)
foodListView.adapter = adapter
foodListView.layoutManager = LinearLayoutManager(this)
}
override fun alertDialog(position: Int) {
val dialog = AlertDialog.Builder(this)
dialog.setTitle("Item deletion")
dialog.setMessage("Do you want to delete this item?")
dialog.setPositiveButton("Yes", DialogInterface.OnClickListener { _, _ ->
adapter.removeItem(position)
})
dialog.setNegativeButton("No", DialogInterface.OnClickListener { _, _ ->
})
dialog.setNeutralButton("Cancel", DialogInterface.OnClickListener { _, _ ->
})
dialog.show()
}
}
FoodDataAdapter:
class FoodDataAdapter(var list: ArrayList<FoodModel>, var listener : FoodDataAdapter.OnItemClickListener):RecyclerView.Adapter<FoodDataAdapter.FoodDataViewHolder>(){
interface OnItemClickListener {
fun alertDialog(position : Int)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FoodDataViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_food,parent,false)
return FoodDataViewHolder(view)
}
override fun getItemCount(): Int {
return list.count()
}
fun removeItem(position: Int) {
list.removeAt(position)
notifyItemRemoved(position)
}
override fun onBindViewHolder(holder: FoodDataViewHolder, position: Int) {
holder.nameText.text=list[position].name
holder.priceText.text="${list[position].price}dollar"
}
inner class FoodDataViewHolder(containerView: View) : RecyclerView.ViewHolder(containerView),
View.OnClickListener {
var nameText: TextView = containerView.findViewById(R.id.nameText)
var priceText: TextView = containerView.findViewById(R.id.priceText)
init {
containerView.setOnClickListener(this)
}
override fun onClick(v: View?) {
listener.alertDialog(adapterPosition)
}
}
}

I just put a declare code for 'removeAt' at the end of the Adapter like this,
class FoodDataAdapter(val list: List<FoodModel>,var itemClicklistener : OnItemClickListener):RecyclerView.Adapter<FoodDataAdapter.FoodDataViewHolder>() {
interface OnItemClickListener {
fun onItemClick(position: Int)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FoodDataViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_food, parent, false)
return FoodDataViewHolder(view)
}
override fun getItemCount(): Int {
return list.count()
}
fun removeItem(position: Int) {
list.removeAt(position)
notifyItemRemoved(position)
}
override fun onBindViewHolder(holder: FoodDataViewHolder, position: Int) {
holder.nameText.text = list[position].name
holder.priceText.text = "${list[position].price} dollar"
}
inner class FoodDataViewHolder(containerView: View) : RecyclerView.ViewHolder(containerView),
View.OnClickListener {
var nameText: TextView = containerView.findViewById(R.id.nameText)
var priceText: TextView = containerView.findViewById(R.id.priceText)
init {
containerView.setOnClickListener(this)
}
override fun onClick(v: View?) {
itemClicklistener.onItemClick(adapterPosition)
}
}
}
private fun Any.removeAt(position: Int) {
}
and also changed the Main activity like this.
class MainActivity : AppCompatActivity(), FoodDataAdapter.OnItemClickListener {
private val foodList = arrayListOf(
FoodModel("Noodle", 3),
FoodModel("Cake", 5),
FoodModel("Pizza", 7),
FoodModel("Stake", 8),
FoodModel("Chicken", 8)
)
var adapter: FoodDataAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
adapter = FoodDataAdapter(foodList, this)
foodListView.adapter = adapter
foodListView.layoutManager = LinearLayoutManager(this)
}
override fun onItemClick(position: Int) {
val dialog = AlertDialog.Builder(this)
dialog.setTitle("Item deletion")
dialog.setMessage("Do you want to delete this item?")
dialog.setPositiveButton("Yes", DialogInterface.OnClickListener { _, _ ->
adapter?.removeItem(position)
})
dialog.setNegativeButton("No", DialogInterface.OnClickListener { _, _ ->
})
dialog.setNeutralButton("Cancel", DialogInterface.OnClickListener { _, _ ->
})
dialog.show()
}
}
And it works! but...one problem is..
after deletion of the list, the last list keep comes up.
the total number of list was not decreased..
lol
another 'Chicken' comes up..do you know how to fix it?

Related

Recyclerview does not display on the screen in kotlin

So I tried to create multi views recyclerview in kotlin, but sadly it did not work.The recyclerview does not display on the screen. It worth to mention that I tried to set the orientation as vertical in my layout files, also added all the dependencies and things needed. Can anyone please help me with that?
My MainActivity.class
#AndroidEntryPoint
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
lateinit var adapter: NumbersAdapter
lateinit var recyclerView: RecyclerView
var list: List<Nums> = listOf(Nums(1,false))
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
updateAll()
}
fun updateAll(){
binding.recyclerview.apply {
val layoutManager = LinearLayoutManager(this#MainActivity)
adapter = NumbersAdapter(list)
adapter = adapter
}}}
My Adapter
class NumbersAdapter(
var list: List<Nums>,
): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
class RedViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val name = itemView.findViewById<TextView>(R.id.red_number)
fun bindRed(number: Nums) {
name.text = number.nums.toString()
}
}
class OrangeViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val name = itemView.findViewById<TextView>(R.id.orange_number)
fun bindOrange(number: Nums) {
name.text = number.nums.toString()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
if (viewType == 0) {
val redvView =
LayoutInflater.from(parent.context).inflate(R.layout.red_item, parent, false)
return RedViewHolder(redvView)
}
else {
val orangeView =
LayoutInflater.from(parent.context).inflate(R.layout.orange_item, parent, false)
return OrangeViewHolder(orangeView)
}
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if(getItemViewType(position)==0){
(holder as RedViewHolder).bindRed(list[position])
}
else{
(holder as OrangeViewHolder).bindOrange(list[position])
}
}
override fun getItemViewType(position: Int): Int {
checkItem()
if(list[position].flag)
return 0
return 1
}
fun checkItem(){
for (i in list.indices) {
for (k in i + 1 until list.size) {
if (list[i].nums + list[k].nums == 0) {
list[i].flag = true
list[k].flag = true
}}}}}
in MainActivity.class change code in updateAll() function
fun updateAll(){
binding.recyclerView.apply {
adapter = NumbersAdapter(list)
layoutManager = LinearLayoutManager(this#MainActivity)
}
}

How to call a method of a fragment from adapter class?

I have seen many questions like this but they are not the same as my situation and I couldn't use those solutions.
I have a fragment (OrdersByStatusFragment.kt) and the method I want to call from the adapter is getOrderStatusList()
class OrdersByStatusFragment : BaseFragment() {
private lateinit var binding: OrderStatusLayoutBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_orders_by_status, container, false)
}
override fun onResume() {
super.onResume()
getOrderStatusList()
}
fun getOrderStatusList() {
showProgressDialog(resources.getString(R.string.please_wait))
FirestoreClass().getOrderStatusList(this#OrdersByStatusFragment)
}
fun successOrderStatusList(orderStatusList: ArrayList<OrderStatus>) {
hideProgressDialog()
if (orderStatusList.size > 0) {
rv_order_by_status.visibility = View.VISIBLE
tv_no_orders_by_status_found.visibility = View.GONE
rv_order_by_status.layoutManager = LinearLayoutManager(activity)
rv_order_by_status.setHasFixedSize(true)
val orderStatusListAdapter =
OrderStatusListAdapter(requireActivity(), orderStatusList)
rv_order_by_status.adapter = orderStatusListAdapter
} else {
rv_order_by_status.visibility = View.GONE
tv_no_orders_by_status_found.visibility = View.VISIBLE
}
}
fun successNewOrderStatus() {
Toast.makeText(requireContext(), "Success", Toast.LENGTH_SHORT).show()
}
}
Adapter OrderStatusListAdapter.kt
open class OrderStatusListAdapter(
private val context: Context,
private var list: ArrayList<OrderStatus>,
) : RecyclerView.Adapter<OrderStatusListAdapter.MyViewHolder>() {
class MyViewHolder(var binding: OrderStatusLayoutBinding) :
RecyclerView.ViewHolder(binding.root)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(
OrderStatusLayoutBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val model = list[position]
if (true) {
GlideLoader(context).loadProductPicture(
model.image,
holder.itemView.iv_order_status_item_image
)
val dateFormat = "dd MMM yyyy HH:mm"
val formatter = SimpleDateFormat(dateFormat, Locale.getDefault())
val calendar: Calendar = Calendar.getInstance()
calendar.timeInMillis = model.order_datetime
val orderDateTime = formatter.format(calendar.time)
holder.itemView.tv_order_status_order_date.text = orderDateTime
holder.itemView.tv_order_status_item_name.text = model.items[0].title
holder.itemView.tv_order_status_item_price.text = "$${model.total_amount}"
holder.itemView.tv_order_status.text = model.order_status
holder.itemView.tv_order_status_order_id.text = model.id
holder.binding.spnOrderChangeStatus.onItemSelectedListener =
object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
holder.binding.tvSpinnerValue.text =
parent?.getItemAtPosition(position).toString()
}
override fun onNothingSelected(parent: AdapterView<*>?) {
}
}
holder.binding.btnOrderStatusChangeStatus.setOnClickListener {
Toast.makeText(context, "Button Clicked", Toast.LENGTH_SHORT).show()
FirestoreClass().updateOrderStatus(
model.id,
holder.binding.tvSpinnerValue.text.toString()
)
Toast.makeText(context, "DB Updated", Toast.LENGTH_SHORT).show()
}
holder.itemView.ib_order_status_delete_product.visibility = View.GONE
holder.itemView.setOnClickListener {
val intent = Intent(context, SoldProductDetailsActivity::class.java)
intent.putExtra(Constants.EXTRA_SOLD_PRODUCT_DETAILS, model)
context.startActivity(intent)
}
}
}
}
As you can see the fun getOrderStatusList() in the OrdersByStatusFragment.kt is actually calling a method in the FirestoreClass.kt. Following is the getOrderStatusList() in the FirestoreClass.kt
fun getOrderStatusList(fragment: OrdersByStatusFragment) {
mFireStore.collection(Constants.ORDERS)
.whereIn("order_status", listOf("Pending", "In process"))
.get()
.addOnSuccessListener { document ->
val list: ArrayList<OrderStatus> = ArrayList()
for (i in document.documents) {
val orderStatus = i.toObject(OrderStatus::class.java)!!
orderStatus.id = i.id
list.add(orderStatus)
}
fragment.successOrderStatusList(list)
}
.addOnFailureListener {
fragment.hideProgressDialog()
}
}
The way I solved something like this is to pass a reference to the method into the adapter's constructor, then you can call the method in the adapter.
See kotlin-how-to-pass-a-function-as-parameter-to-another
In general, the link shows a class containing a method called buz.
Let's say your adapter has a constructor like:
class MyAdapter (private val context: Context, val buzz: () -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>()
then you can create the adapter like
MyAdapter(applicationContext, ::buz)
In the adapter the method can be called normally:
buzz()

Spiner into RecyclerView item - kotlin

i have problem with adding simple Spiner to RecyclerView item. I saw a lot of examples but i cannot add it to my project. All i want is the same Spiner with list of Strings in every item of RecyclerView. I have no problem with implement this without RecycylerView, but with it, i dont know where to pass Adapter for Spiner.
RecyclerViewAdapter:
class MealPlanerAdapter(val mealList: MutableList<String>) : RecyclerView.Adapter<CustomViewHolder>() {
val mealCalories = mutableListOf<Int>()
override fun getItemCount(): Int {
return mealList.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val cellForRow = layoutInflater.inflate(R.layout.meal_row, parent, false)
mealList.forEach {
mealCalories.add(100 / mealList.size)
}
return CustomViewHolder(cellForRow)
}
#SuppressLint("SetTextI18n", "CutPasteId", "ClickableViewAccessibility")
override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
holder.view.findViewById<TextView>(R.id.meal_name_text_view).text = "Meal name"
holder.view.findViewById<TextView>(R.id.calosies_slider_name_text_view).text = "Daily calories: "
holder.view.findViewById<TextView>(R.id.calories_value_text_view).text = holder.view.findViewById<SeekBar>(
R.id.calories_seek_bar
).progress.toString()+"%"
holder.view.findViewById<TextView>(R.id.protein_value_text_view).text = holder.view.findViewById<SeekBar>(
R.id.protein_seek_bar
).progress.toString()+"%"
holder.view.findViewById<TextView>(R.id.fat_value_text_view).text = holder.view.findViewById<SeekBar>(
R.id.fat_seek_bar
).progress.toString()+"%"
holder.view.findViewById<TextView>(R.id.carbs_value_text_view).text = holder.view.findViewById<SeekBar>(
R.id.calories_seek_bar
).progress.toString()+"%"
holder.view.findViewById<SeekBar>(R.id.calories_seek_bar).progress = mealCalories[position]
var proteinValue: Int = 20
var fatValue: Int = 25
holder.view.findViewById<SeekBar>(R.id.calories_seek_bar).setOnSeekBarChangeListener(object :
SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(
seekBar: SeekBar?,
progress: Int,
fromUser: Boolean
) {
holder.view.findViewById<TextView>(R.id.calories_value_text_view).text =
"$progress%"
println(position)
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
}
})
holder.view.findViewById<SeekBar>(R.id.protein_seek_bar).setOnSeekBarChangeListener(object :
SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
holder.view.findViewById<TextView>(R.id.protein_value_text_view).text = "$progress%"
proteinValue = progress
holder.view.findViewById<SeekBar>(R.id.carbs_seek_bar).progress =
100 - proteinValue - fatValue
holder.view.findViewById<SeekBar>(R.id.carbs_seek_bar).refreshDrawableState()
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
}
})
holder.view.findViewById<SeekBar>(R.id.fat_seek_bar).setOnSeekBarChangeListener(object :
SeekBar.OnSeekBarChangeListener {
#SuppressLint("ResourceType")
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
holder.view.findViewById<TextView>(R.id.fat_value_text_view).text = "$progress%"
fatValue = progress
holder.view.findViewById<SeekBar>(R.id.carbs_seek_bar).progress =
100 - proteinValue - fatValue
holder.view.findViewById<View>(R.id.carbs_seek_bar).refreshDrawableState()
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
}
})
holder.view.findViewById<SeekBar>(R.id.carbs_seek_bar).setOnTouchListener { v, event -> true }
}
}
class CustomViewHolder(val view: View): RecyclerView.ViewHolder(view) {
}
Fragment:
class MealPlanerFragment : Fragment(R.layout.fragment_meal_planer) {
private var param1: String? = null
private var param2: String? = null
private val mealList = mutableListOf<String>("1", "2", "3")
private lateinit var mAdapter: MealPlanerAdapter
private lateinit var mLinearLayoutManager: LinearLayoutManager
private lateinit var mRecyclerView: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
mAdapter = MealPlanerAdapter(mealList)
}
#SuppressLint("CutPasteId", "ResourceType")
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val inflater = inflater.inflate(R.layout.fragment_meal_planer, container, false)
mLinearLayoutManager = LinearLayoutManager(activity)
mRecyclerView = inflater.findViewById(recycler_view_meal_planer)
mRecyclerView.layoutManager = mLinearLayoutManager
mRecyclerView.adapter = mAdapter
return inflater
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
}

Receive data from Adapter to DetailsActivity?

I want to know how I can receive the data from adapter (recyclerview) to DetailsActivity. I tried many times but the images from recyclerview doesn't show in DetailsActivity.
this is my code.
ImageAdapter
class ImageAdapter (private var items:List<Item>, private val context:Context):
RecyclerView.Adapter<ImageAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int):ViewHolder {
return ViewHolder(
LayoutInflater.from(context).inflate(R.layout.item, parent, false)
)
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: ImageAdapter.ViewHolder, position: Int) {
val item = items[position]
Picasso.get().load(item.imageUrl).into(holder.imageView)
holder.imageView.setOnClickListener {
val intent = Intent(context, DetailsActivity::class.java)
intent.putExtra("iImages", item.imageUrl)
context.startActivity(intent)
}
}
class ViewHolder(view:View):RecyclerView.ViewHolder(view) {
val imageView : ImageView = view.findViewById(R.id.imageView)
}
}
DetailsActivity
class DetailsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_details)
val aImageView = intent.getIntExtra("iImages", 0)
details_image.setImageResource(aImageView)
}
}
RecyclerActivity
class RecyclerActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recycler)
val storage = FirebaseStorage.getInstance()
val storageRef = storage.reference.child("wallpapers")
val imageList : ArrayList<Item> = ArrayList()
//progressBar.visibility = View.VISIBLE
val listAllTask : Task<ListResult> = storageRef.listAll()
listAllTask.addOnCompleteListener { result ->
val items: List<StorageReference> = result.result!!.items
//add cycle for add image url to list
items.forEachIndexed { index,item ->
item.downloadUrl.addOnSuccessListener {
Log.d("item", "$it")
imageList.add(Item(it.toString()))
}.addOnCompleteListener {
recyclerview.adapter = ImageAdapter(imageList, this)
recyclerview.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
//progressBar.visibility = View.GONE
}
}
}
}
}
Item
data class Item(
var imageUrl: String
)
The problem is this line:
details_image.setImageResource(aImageView)
You are setting a resource int but what you pass seems to be a url, so instead load the "iImages" value with Picasso for that view
Edit: Replace this:
val aImageView = intent.getIntExtra("iImages", 0)
details_image.setImageResource(aImageView)
with this
val retrievedImageUrl = intent.getIntExtra("iImages", 0)
Picasso.get().load(retrievedImageUrl).into(details_image)
The Answer
val imageView : ImageView = findViewById(R.id.details_image)
Glide.with(this).load(intent.getStringExtra("iImages")).into(imageView)

RecyclerView onClick in kotlin

I'm new android learner, I'm trying to make a RecyclerView contains of List of (Stories Title, and Stories images).
When you click on an item in the RecyclerView it should open a new activity called ChildrenStoriesPreview contains of ScrollView which have ImageView to put the Story Image in it and TextView to put the Text of the Story in it.
the problem is that I don't know how to set ocItemClickListener to know which item is clicked and how the new activity will contain information depending on this item? Could you please help me?
here is my Main.kt
class MainChildrenStories : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_children_stories)
var childrenStoriesArraylist = ArrayList<ChildrenStoriesRecyclerView>()
childrenStoriesArraylist.add(ChildrenStoriesRecyclerView("Story1", R.drawable.pic1))
childrenStoriesArraylist.add(ChildrenStoriesRecyclerView("Story2", R.drawable.pic2))
childrenStoriesArraylist.add(ChildrenStoriesRecyclerView("Story3", R.drawable.pic3))
children_stories_recyclerview.layoutManager = LinearLayoutManager(this, LinearLayout.VERTICAL, false)
val childrenStoriesAdapter = ChildrenStoriesAdapter(childrenStoriesArraylist)
children_stories_recyclerview.adapter = childrenStoriesAdapter
childrenStoriesAdapter.setOnItemClickListener(object : ChildrenStoriesAdapter.ClickListener {
override fun onClick(pos: Int, aView: View) {
//The App Crash here
if (pos == 0){
my_text_view.text = "Story number 1"
my_imageview.setImageResource(R.drawable.pic1)
}else if (pos == 1){
my_text_view.text = "Story number 2"
my_imageview.setImageResource(R.drawable.pic2)
}
val intent = Intent(this#MainChildrenStories, ChildrenStoryPreview::class.java)
startActivity(intent)
}
})
}
}
MyRecyclerView Class
data class ChildrenStoriesRecyclerView(var mStoryName: String, var mStoryImage: Int)
My RecyclerView Adapter Class
class ChildrenStoriesAdapter(var myArrayList: ArrayList<ChildrenStoriesRecyclerView>) :
RecyclerView.Adapter<ChildrenStoriesAdapter.ViewHolder>() {
lateinit var mClickListener: ClickListener
fun setOnItemClickListener(aClickListener: ClickListener) {
mClickListener = aClickListener
}
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ViewHolder {
val v = LayoutInflater.from(p0.context).inflate(R.layout.children_stories_list, p0, false)
return ViewHolder(v)
}
override fun getItemCount(): Int {
return myArrayList.size
}
override fun onBindViewHolder(p0: ViewHolder, p1: Int) {
var infList = myArrayList[p1]
p0.storyName.text = infList.mStoryName
p0.storyImage.setImageResource(infList.mStoryImage)
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
override fun onClick(v: View) {
mClickListener.onClick(adapterPosition, v)
}
val storyName = itemView.findViewById(R.id.txtStoryName) as TextView
val storyImage = itemView.findViewById(R.id.imageViewChildrenStories) as ImageView
init {
itemView.setOnClickListener(this)
}
}
interface ClickListener {
fun onClick(pos: Int, aView: View)
}
}
My new Activity To show Details of the Story
class ChildrenStoryPreview : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_children_story_preview)
}
}
Pass the Event Listener to Adapter constructor also to viewholder to catch view holder (items) clicks.
class ChildrenStoriesAdapter(var myArrayList: ArrayList<ChildrenStoriesRecyclerView>
var clickListener:MyClickListener?) :
RecyclerView.Adapter<ChildrenStoriesAdapter.ViewHolder>() {
...
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ViewHolder {
val v = LayoutInflater.from(p0.context).inflate(R.layout.children_stories_list, p0, false)
return ViewHolder(v, clickListener)
}
...
inner class ViewHolder(itemView: View, clickListener:MyClickListener?) :
RecyclerView.ViewHolder(itemView) {
itemView.setOnClickListener { clickListener?.myClickedFun(...) }
...
class ChildrenStoryPreview : AppCompatActivity(), MyClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_children_story_preview)
}
override fun myClickedFun(...) {
...
}
}
Later init adapter like
..
val childrenStoriesAdapter = ChildrenStoriesAdapter(childrenStoriesArraylist, this)