How to enable user to choose icon for an item in recyclerview?

68 Views Asked by At

I'm building a simple groceries app. When user cliks on fab, DialogFragment is shown with input text with name, brand and quantity. I would like the user to also choose icon of the product he wants to add to the grocery list. How can I do it? It should be a list of icons that I will have stored in my DB.

1

There are 1 best solutions below

0
Majd Haj Hmedy On

To store an icon in your database object, just create a new parameter for the data class object

data class Grocery(
val name: String = "",
val brand: String = "",
val quantity: Int = 0,
val icon: Int = 0)  

In case you're wondering why the icon parameter is of type Int then it's because when you pass the icon to the Grocery class it's going to look like this

R.drawable.some_icon  

And this returns an Int. That it's it for the data part, and for listing the icons in a recycler view inside a dialog, you can just create an object (usually named Constants) that has a function to return your preferred icons

object Constants{
    fun getIcons(): List<Int>{
        val iconsList = listOf<Int>(
            R.drawable.icon1,
            R.drawable.icon2,
            R.drawable.icon3,
            ...
        )
        return iconsList
    }
}  

Now you can create a recycler view and pass this list to the adapter and just set the imageView ImageDrawable at the current position of the recycler view.
Good luck with your app!