I have an app in which depending on the currency selected, I pass the list to the adapter and based on the type of list passed as an argument, I decide which model class should be used.
RecyclerView Adapter
class CoinAdapter : RecyclerView.Adapter<CoinAdapter.MyViewHolder> {
private var coinList: List<Coin>? = null
private var coinINRList: List<CoinINR>? = null
private var coinEURList: List<CoinEUR>? = null
private var coinGBPList: List<CoinGBP>? = null
private var context: Context? = null
inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var coinName: TextView
var coinPrice: TextView
init {
coinName = view.findViewById(R.id.coin_title_text)
coinPrice = view.findViewById(R.id.coin_price_text)
}
}
constructor(coinList: List<Coin>?, context: Context?) {
this.coinList = coinList
this.context = context
}
constructor(coinList: List<CoinINR>?, context: Context?, second: String) {
this.coinINRList = coinList
this.context = context
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.coin_list_row, parent, false)
return MyViewHolder(itemView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
when (currencyUnit) {
"USD" -> {
val coin = coinList?.get(position)
holder.coinName.text = coin?.name
holder.coinPrice.text = coin?.price
}
"INR" -> {
val coinINR = coinINRList?.get(position)
holder.coinName.text = coinINR?.name
holder.coinPrice.text = coinINR?.price
}
}
}
override fun getItemCount(): Int {
when (currencyUnit) {
"USD" -> return coinList?.size ?: 0
"INR" -> return coinINRList?.size ?: 0
else -> return coinList?.size ?: 0
}
}
}
Now, I need to support multiple currencies and so the code is becoming boilerplate. Is there any way that I can make the RecyclerView accept any type of list and then perform task depending on the list?
Thanks in advance.
My suggestion is to create a class Coin that will be a parent of all other currency objects.
open class Coin(val name: String, val price: Float)
data class CoinINR(name: String, price: Float) : Coin(name, price)
Than your adapter would have only one List and your onBindViewHolder method will look like this:
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
with (coinList?.get(position)) {
holder.coinName.text = it.name
holder.coinPrice.text = it.price
}
}
Related
I have one RecyclerView, and if I click one item of it, I want make Data of RecyclerView change.
companion object {
var regionData: MutableLiveData<List<String>> = MutableLiveData()
var smallRegionScreen : Boolean = false
}
So I use MutableLiveData to make Data mutable and keep being observed.
adapter = regionData.value?.let { RegionAdapter(this, it, smallRegionScreen) }!!
I pass regionData.value as Data of Adapter, whose type will be List. And smallRegionScreen is Boolean value.
Since first click of item and second click of item in RecyclerView's taken action will be different, so I differentiate it by this value.
regionDB.get()
.addOnSuccessListener { documents ->
for (document in documents) {
var newArray = ArrayList<String>()
Log.d("리지온1", "$document")
for ((k, v) in document.data) {
regionData.value.add(v.String)
Log.d("리지온", "${regionData.value}")
}
}
adapter.notifyDataSetChanged()
}
binding.regionRecycler.adapter=adapter
binding.regionRecycler.layoutManager= LinearLayoutManager(this)
}
As here, I add item to regionData.value.
But it shows empty Array.
What is problem here?
And My Adapter is below, my process is okay?
class RegionAdapter(private var context: Context, private var regionData: List<String>, private var smallRegionScreen: Boolean): RecyclerView.Adapter<RegionAdapter.RegionViewHolder>() {
var userDB = Firebase.firestore.collection("users")
var userId = Firebase.auth.currentUser?.uid
companion object {
var REGION_RECYCLER_CLICKED = "com.chungchunon.chunchunon_android.REGION_RECYCLER_CLICKED"
}
inner class RegionViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) {
val regionView: TextView = itemView.findViewById(R.id.regionSelectText)
fun bind (position: Int) {
regionView.text = regionData[position]
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RegionViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_region, parent, false)
return RegionViewHolder(view)
}
override fun onBindViewHolder(holder: RegionViewHolder, position: Int) {
holder.bind(position)
holder.itemView.setOnClickListener { view ->
if(!smallRegionScreen) {
var selectedRegion = regionData[position]
var regionSet = hashMapOf(
"region" to selectedRegion
)
userDB.document("$userId").set(regionSet)
var regionDB = Firebase.firestore.collection("region")
regionDB
.document("4ggk4cR82mz46CjrLg60")
.collection(selectedRegion.toString())
.get()
.addOnSuccessListener { documents ->
for (document in documents) {
for ((k, v) in document.data) {
regionData.plus(v.toString())
}
}
smallRegionScreen = true
}
} else {
var selectedSmallRegion = regionData[position]
var regionSet = hashMapOf(
"smallRegion" to selectedSmallRegion
)
userDB.document("$userId").set(regionSet)
}
}
}
override fun getItemCount(): Int {
return regionData.size
}
}
If you want to add data to your MutableLiveData:
val regionDataList = regionData.value
val templateList = mutableListOf<String>()
regionDataList?.forEach { data ->
templateList.add(data)
}
templateList.add(v.String)
regionData.value = templateList
you can add data in the list like this :-
regionData.value.add(v.toString())
I have an app which uses Room Database to show data in recycleview. It works fine when i load data seperately from different tables. But i want to show data from both tables in a single recycleview with multiple viewtypes, i know how to combine tables in room but it's not working. I get empty cards in recycleview when i load the data. Here is what i have tried so far.
My Adapter Class
class CategoriesAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
private const val TYPE_CATEGORIES = 0
private const val TYPE_ARTICLES = 1
}
private val items: MutableList<Any> by lazy {
ArrayList<Any>()
}
fun setItems(list: List<Any>) {
items.addAll(list)
notifyDataSetChanged()
}
override fun getItemViewType(position: Int): Int {
return if (items[position] is Categories) TYPE_CATEGORIES else TYPE_ARTICLES
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
TYPE_CATEGORIES -> CategoriesViewHolder.create(viewGroup)
else -> ArticlesViewHolder.create(viewGroup)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is CategoriesViewHolder -> {
if (items[position] is Categories)
holder.bind(items[position] as Categories)
}
is ArticlesViewHolder -> {
if (items[position] is Articles)
holder.bind(items[position] as Articles)
}
}
}
override fun getItemCount(): Int {
return items.size
}
}
class CategoriesViewHolder (parent: View) : RecyclerView.ViewHolder(parent) {
val textView: TextView = parent.findViewById(R.id.categories_textView)
fun bind(category: Categories) {
textView.text = category.categoryName
}
companion object {
fun create(parent: ViewGroup): CategoriesViewHolder {
return CategoriesViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.categories_item_layout, parent, false))
}
}
}
class ArticlesViewHolder (parent: View) : RecyclerView.ViewHolder(parent) {
val textView: TextView = parent.findViewById(R.id.titleText)
fun bind(articles : Articles) {
textView.text = articles.articleName
}
companion object {
fun create(parent: ViewGroup): ArticlesViewHolder {
return ArticlesViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.article_item_layout, parent, false))
}
}
}
this is how i set data from my activity
val db = AppDatabase.getDatabase(applicationContext)
dao = db.articleDao()
val recyclerView = findViewById<RecyclerView>(R.id.categories_recycle_view)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = CategoriesAdapter()
adapter.setItems(dao.getAllArticlesAndCategories())
Can anyone help.
P.s i'm new to kotlin
Instead of
adapter.setItems(dao.getAllArticlesAndCategories())
Use live data observer to avoid processing on main thread and debug in observe function of live data to confirm you are receiving correct data from DB.
calling code one line of code is missing
val db = AppDatabase.getDatabase(applicationContext)
dao = db.articleDao()
val recyclerView = findViewById<RecyclerView>(R.id.categories_recycle_view)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = CategoriesAdapter()
adapter.setItems(dao.getAllArticlesAndCategories())
it should be:
val db = AppDatabase.getDatabase(applicationContext)
dao = db.articleDao()
val recyclerView = findViewById<RecyclerView>(R.id.categories_recycle_view)
recyclerView.layoutManager = LinearLayoutManager(this)
adapter=CategoriesAdapter()
adapter.setItems(dao.getAllArticlesAndCategories())
recyclerView.adapter = adapter
I would like to thank for the question and the code
I want to create an android app with Kotlin. In this app, i use swagger also to get all the web service in a file.
I want to create an interface, the description is as follows:
A RecyclerView horizontal that contains all the list of categories
comes from a web service apiMobileProductCategoriesGetAllPost.
after that, when i click on a which category, a RecyclerView(Grid)
appear that contains all the product by category id.
I want to know how can i get the category id when i click on item,and how to use it in the activity
The following the RecyclerView category adapter:
class CategoryAdapter(private val categories: Array<ProductCategoryData>) :
RecyclerView.Adapter<CategoryAdapter.ViewHolder>(), View.OnClickListener {
private var onItemClickListener: OnItemClickListener? = null
override fun onClick(v: View?) {
if (v != null) {
onItemClickListener?.onItemClick(v, ProductCategoryData())
}
}
fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
this.onItemClickListener = onItemClickListener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.category_item, parent, false)
view.setOnClickListener(this)
return ViewHolder(view)
}
override fun getItemCount() = categories.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val itemCategory: ProductCategoryData = categories[position]
holder.categoryId.text = itemCategory.id.toString()
println(holder.categoryId.text)
println(itemCategory.name?.get("En").toString())
holder.categoryName.text = itemCategory.name?.get("En").toString()
println(itemCategory.id)
if (itemCategory.logo != null) {
Picasso.get()
.load("..../T/${itemCategory.logo}")
.into(holder.categoryImage, object : com.squareup.picasso.Callback {
override fun onError(e: Exception?) {
holder.categoryImage.setImageResource(R.drawable.homecraftdefault)
}
override fun onSuccess() {
Picasso.get().load("....T/${itemCategory.logo}")
.into(holder.categoryImage)
}
})
holder.itemView.setOnClickListener {
onItemClickListener?.onItemClick(holder.itemView,itemCategory)
}
}
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
val categoryName: TextView = itemView.categoryName
val categoryImage: ImageView = itemView.categoryImage
val categoryId: TextView = itemView.categoryId
override fun onClick(v: View?) {
if (v != null) {
onItemClickListener?.onItemClick(v, ProductCategoryData())
}
}
}
interface OnItemClickListener {
fun onItemClick(view : View, viewModel:ProductCategoryData)
}
}
The following code is relative to the activity:
class CategoryByProduct : AppCompatActivity(), CategoryAdapter.OnItemClickListener {
override fun onItemClick(view: View, viewModel: ProductCategoryData) {
var params = "CategoryProductID";"5cc057458c4d9823743736d2"
println(viewModel.id)
val products = mobileApi!!.apiMobileProductsGetAllPost(params, 0, 50, "", "")
recyclerViewProductByCategory.apply {
recyclerViewProductByCategory.layoutManager = GridLayoutManager(this#CategoryByProduct, 2)
recyclerViewProductByCategory.adapter = ProductAdapter(products)
} }
var mobileApi: MobileApi? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.list_product_by_category)
mobileApi = MobileApi()
val params = HashMap<String, String>()
GlobalScope.launch(Dispatchers.IO) {
val categories = mobileApi!!.apiMobileProductCategoriesGetAllPost(params, 0, 50, "", "")
withContext(Dispatchers.Main) {
recyclerViewCategories.apply {
recyclerViewCategories.layoutManager =
LinearLayoutManager(this#CategoryByProduct, OrientationHelper.HORIZONTAL, false)
recyclerViewCategories.adapter = CategoryAdapter(categories)
}
}
}
}
}
First of all , never put your onclick in onBindViewHolder That's not a good practice, after that i think you need to get the ID of the category i will give you simple example in all of the Adapter Class
class NewsAdapter (val context: Context, private val arrayList: ArrayList <NewsModel>):
RecyclerView.Adapter <NewsAdapter.Holder> () {
companion object {
// val TAG: String = OperationAdapter::class.java.simpleName
}
override fun onCreateViewHolder (parent: ViewGroup, viewType: Int): Holder {
return Holder (LayoutInflater.from (parent.context ).inflate (R.layout.newslist , parent, false))
}
override fun getItemCount (): Int = arrayList. size
override fun onBindViewHolder (holder: Holder, position: Int) {
val mynews = arrayList[position]
holder.setData(mynews , position)
}
inner class Holder (itemView: View): RecyclerView.ViewHolder (itemView) {
private var currentnews: NewsModel? = null
private var currentPosition: Int = 0
init {
//The click listener
itemView.newscardview.setOnClickListener {
//do it here
Toast.makeText(this,currentnews!!.id,Toast.LENGTH_SHORT).show()
}
//the end of the init
}
//getting data from model and bind it into View
fun setData(news: NewsModel?, position: Int) {
news?.let {
itemView.newsid.text = news.id
itemView.newstitle.text = news.title
itemView.body.text = news.body
itemView.txtdate.text = news.ndate
}
this.currentnews = news
this.currentPosition = position
}
}
}
In this example you will get the news ID when you click newscardview, i hope to understand it
In your Activity
put this code in onCreate
//set up the recycleview
mRecyclerView.setHasFixedSize (true)
mRecyclerView. layoutManager = LinearLayoutManager(this)
mRecyclerView is my RecycleView
also call your Adapter class in anywhere you want
//adapter
val adapter = NewsAdapter (this,arrayList)
adapter.notifyDataSetChanged()
mRecyclerView.adapter = adapter
you get the position of the category inside a viewholder by calling adapterPosition and with this you can get the category from your list you provide to your adapter in the constructor (categories[adapterPosition])
In your case it is very simple.Try these:-
holder.tv_broadcast_title.text=broadList[position].name
where broadlist is my array list created in the adapter itself.In this list the json data is getting stored from api.
internal var broadList = ArrayList<Model>()
and .name is the name of key to fetch name from json data.
holder.categoryName.text = itemCategory.name?.get("En").toString()
in your case do something like this:-
itemCategory[position].name
To get data from adapter to activity, you can make an interface in the adapter or globally and from the activity you can pass that interface in adapter's constructor and use that to get data. I am giving you an example.
interface ProductCategoryListner {
fun getProductCategory(viewModel:ProductCategoryData)
}
Not in adapter's constructor add this interface.
class CategoryAdapter(private val categories: Array<ProductCategoryData>,private val productCategoryListner: ProductCategoryListner):
RecyclerView.Adapter<CategoryAdapter.ViewHolder>(), View.OnClickListener {
Now you can use this to pass data in the activity when you click on view.
productCategoryListner.getProductCategory(categories[adapterPosition])
Hey guys i have this problem in android studio i just use Recycleview component and i did everything right but still Nothing Display in simulator anyone can help look up on my code..all items are just picked up from database.
item adapter for recycleview (itemadapter.kt)
class ItemAdapter (var context: Context,var list:ArrayList):
RecyclerView.Adapter(){ override fun onCreateViewHolder(parent: ViewGroup,
viewType: Int): RecyclerView.ViewHolder { var
v:View=LayoutInflater.from(context).inflate(R.layout.item_row,parent) return
ItemHolder(v) }
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position:
Int) {
(holder as ItemHolder).bind(list[position].name,list[position].price,list[position].photo)
}
class ItemHolder(itemView:View):RecyclerView.ViewHolder(itemView)
{
fun bind(n:String,p:String,u:String)
{
itemView.item_name.text =n
itemView.item_price.text=p
var web:String=" http://192.168.43.14/delivery/images/"+ u
web=web.replace("","%20")
Picasso.with(itemView.context).load(web).into(itemView.item_photo)
}
}
}
activity_item.kt
var cat:String=intent.getStringExtra("cat")
var url="http://192.168.43.14/delivery/get_items.php?category= "+cat
var list=ArrayList<Item>()
var rq: RequestQueue = Volley.newRequestQueue(this)
var jar= JsonArrayRequest(Request.Method.GET,url,null, Response.Listener { response ->
for (x in 0..response.length() -1)
list.add(Item(response.getJSONObject(x).getInt("id"),response.getJSONObject(x).getString("name"),
response.getJSONObject(x).getString("price"),response.getJSONObject(x).getString("photo")))
var adp=ItemAdapter(this,list)
item_rv.layoutManager = LinearLayoutManager(this)
item_rv.adapter=adp
}, Response.ErrorListener { error ->
Toast.makeText(this,error.message, Toast.LENGTH_LONG).show()
})
rq.add(jar)
}
}
Item.kt (class file)
class Item{
var id:Int
var name:String
var price:String
var photo:String
constructor(id:Int,name:String,price:String,photo:String)
{
this.id=id
this.name=name
this.price=price
this.photo=photo
}
}
please guys help me out where i mess it up beacause am stuck right there~!
You forgot to notify your list, please add the LOC adp.notifyDataSetChanged()
var adp=ItemAdapter(this,list)
item_rv.layoutManager = LinearLayoutManager(this)
item_rv.adapter=adp
adp.notifyDataSetChanged()
At first take some Tutorial to learn how to make one RecycleView Adapter and Holder:
Your Adapter should look like:
class ItemAdapter (val context: Context, val list:ArrayList<Item>): RecyclerView.Adapter<ItemHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHolder {
val v: View = LayoutInflater.from(context).inflate(R.layout.item_row, parent, false)
//.inflate(R.layout.item_row, parent, false) *false is important
return ItemHolder(v)
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: ItemHolder, position: Int) {
holder.itemName.text = "${list[position].name}"
holder.itemPrice.text = "${list[position].price}"
val web:String="http://192.168.43.14/delivery/images/${list[position].photo}".replace(" ","%20")
Picasso.with(holder.itemView.context).load(web).into(holder.item_photo)
}
}
class ItemHolder(itemView:View):RecyclerView.ViewHolder(itemView) {
val itemName = itemView.item_name
val itemPrice = itemView.item_price
val itemPhoto = itemView.item_photo
}
You can buy me a Coffee :) for next question
FYI
var item = "item VARIABLE"
val item = "item VALUE"
I want to have generic RecyclerView to be able to reuse it. In my case I have 2 models: CategoryImages and Category. While trying to add constructor() it brings the following errors. I know the second one is because it understands like both primary and secondary constructor are same.
Is it possible to do such kind of thing? If yes, then how? if no - thank you.
Here is CategoryImage:
class CategoryImage {
#SerializedName("url")
private var url: String? = null
fun getUrl(): String? {
return url
}
}
And here is Category:
class Category {
#SerializedName("_id")
var id: String? = null
#SerializedName("name")
var name: String? = null
#SerializedName("__v")
var v: Int? = null
#SerializedName("thumbnail")
var thumbnail: String? = null
}
Here is the part of RecyclerViewAdapter's constructor:
class RecyclerViewAdapter(var arrayList: ArrayList<CategoryImage>?, var fragment: Int): RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>() {
constructor(arrayList: ArrayList<Category>, fragment: Int): this(arrayList, fragment)
}
I want to have generic RecyclerView to be able to reuse it.
That's nice intention, then why you haven't made your adapter generic?
I think you can adopt the approach outlined by Arman Chatikyan in this blog post. After applying some Kotlin magic you'll only need following lines of code in order to setup your RecyclerView:
recyclerView.setUp(users, R.layout.item_layout, {
nameText.text = it.name
surNameText.text = it.surname
})
And if you need to handle clicks on RecyclerView items:
recyclerView.setUp(users, R.layout.item_layout, {
nameText.text = it.name
surNameText.text = it.surname
}, {
toast("Clicked $name")
})
Now the adapter of the RecyclerView is generic and you are able to pass list of any models inside setup() method's first argument.
In this section I will copy-paste sources from the blog post, in order to be evade from external sources deprecation.
fun <ITEM> RecyclerView.setUp(items: List<ITEM>,
layoutResId: Int,
bindHolder: View.(ITEM) -> Unit,
itemClick: ITEM.() -> Unit = {},
manager: RecyclerView.LayoutManager = LinearLayoutManager(this.context)): Kadapter<ITEM> {
return Kadapter(items, layoutResId, {
bindHolder(it)
}, {
itemClick()
}).apply {
layoutManager = manager
adapter = this
}
}
class Kadapter<ITEM>(items: List<ITEM>,
layoutResId: Int,
private val bindHolder: View.(ITEM) -> Unit)
: AbstractAdapter<ITEM>(items, layoutResId) {
private var itemClick: ITEM.() -> Unit = {}
constructor(items: List<ITEM>,
layoutResId: Int,
bindHolder: View.(ITEM) -> Unit,
itemClick: ITEM.() -> Unit = {}) : this(items, layoutResId, bindHolder) {
this.itemClick = itemClick
}
override fun onBindViewHolder(holder: Holder, position: Int) {
holder.itemView.bindHolder(itemList[position])
}
override fun onItemClick(itemView: View, position: Int) {
itemList[position].itemClick()
}
}
abstract class AbstractAdapter<ITEM> constructor(
protected var itemList: List<ITEM>,
private val layoutResId: Int)
: RecyclerView.Adapter<AbstractAdapter.Holder>() {
override fun getItemCount() = itemList.size
override fun onCreateViewHolder(parent: ViewGroup,
viewType: Int): Holder {
val view = LayoutInflater.from(parent.context).inflate(layoutResId, parent, false)
return Holder(view)
}
override fun onBindViewHolder(holder: Holder, position: Int) {
val item = itemList[position]
holder.itemView.bind(item)
}
protected abstract fun onItemClick(itemView: View, position: Int)
protected open fun View.bind(item: ITEM) {
}
class Holder(itemView: View) : RecyclerView.ViewHolder(itemView)
}
Assuming CategoryImage means a Category with image.
You can express this relationship with inheritance:
open class Category(
val name: String
)
class CategoryImage(
name: String,
val image: String
) : Category(name)
class RecyclerViewAdapter(
val arr: List<Category>,
val fragment: Int
) {
fun bind(i: Int) {
val item = arr[i]
val name: String = item.name
val image: String? = (item as? CategoryImage)?.image
}
}
Another options it to have a common interface (which removes that ugly cast):
interface CategoryLike {
val name: String
val image: String?
}
class Category(
override val name: String
) : CategoryLike {
override val image: String? = null
}
class CategoryImage(
override val name: String,
override val image: String
) : CategoryLike
class RecyclerViewAdapter(private var arr: List<CategoryLike>, var fragment: Int) {
fun bind(i: Int) {
val item = arr[i]
val name: String = item.name
val image: String? = item.image
}
}
In both cases the following works (just to see that it can be compiled):
fun testCreation() {
val cats: List<Category> = listOf()
val catImages: List<CategoryImage> = listOf()
RecyclerViewAdapter(cats, 0)
RecyclerViewAdapter(catImages, 0)
}
Tip: don't use ArrayList, List (listOf(...)) or MutableList (mutableListOf(...)) should be enough for all your needs.
Tip: try to use val as much as you can, it helps prevent mistakes.
Wish: Next time please also include some relevant parts of your code in a copy-able form (not screenshot), so we don't have to re-type it and have more context. See https://stackoverflow.com/help/mcve
One "terrible" way of doing it is to simply have 1 constructor taking an ArrayList of Objects and perform an instanceof on the objects.
Both methods have the same signature, because type parameters are not considered as different types (for Java Virtual Machine both are just ArrayLists). You also need to be aware of type erasure.
Check this repository https://github.com/shashank1800/RecyclerGenericAdapter
lateinit var adapter: RecyclerGenericAdapter<AdapterItemBinding, TestModel>
...
val clickListener = ArrayList<CallBackModel<AdapterItemBinding, TestModel>>()
clickListener.add(CallBackModel(R.id.show) { model, position, binding ->
Toast.makeText(context, "Show button clicked at $position", Toast.LENGTH_SHORT)
.show()
})
adapter = RecyclerGenericAdapter(
R.layout.adapter_item, // layout for adapter
BR.testModel, // model variable name which is in xml
clickListener // adding click listeners is optional
)
binding.recyclerView.adapter = adapter
binding.recyclerView.layoutManager = LinearLayoutManager(this)
adapter.submitList(viewModel.testModelList)
Recycler adapter item R.layout.adapter_item XML.
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="testModel"
type="com.packagename.model.TestModel" />
</data>
...
VERY IMPORTANT NOTE: I'm using same layout for all my screens.
//********Adapter*********
// include a template parameter T which allows Any datatype
class MainAdapter<T : Any>(var data: List<T>) : RecyclerView.Adapter<MainViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainViewHolder {
val view = parent.inflateLayout()
return MainViewHolder(view)
}
override fun onBindViewHolder(holder: MainViewHolder, position: Int) {
val item = data[position]
holder.bind(item)
}
override fun getItemCount(): Int = data.size
class MainViewHolder(private val binding: MainItemsListBinding) :
RecyclerView.ViewHolder(binding.root) {
// do the same for for bind function on Viewholder
fun <T : Any> bind(item: T) {
// Extension function see code below
binding.appInfo.mySpannedString(item)
}
}
}
//Cast Item to type
fun <T : Any> TextView.mySpannedString(item: T) {
when (item.javaClass.simpleName) {
"AaProgram" -> {
item as AaProgram
this.text = buildSpannedString {
appInfo(item.numero, item.principio)
}
}
"AppContent" -> {
item as AppContent
this.text = buildSpannedString {
appInfo(item.title, item.coment, item.footnote)
}
}
"AutoDiagnostic" -> {
item as AppContent
this.text = buildSpannedString {
appInfo(item.title, item.coment, item.footnote)
}
}
"GroupDirectory" -> {}
"ReflexionsBook" -> {}
"County" -> {}
"States" -> {}
"Towns" -> {}
}
}