Search code examples
androidkotlinadapter

Prevent instantiating items android instantiateItem


Have current fun:

override fun instantiateItem(container: ViewGroup, position: Int): Any {
    val view = AuthorizationHeaderView(context = context)
    updateViewContent(view, data[position])
    timeUpdateListeners.add(view as TimeUpdateListener)
    container.addView(view, 0)
    return view
}

But right now I don't want to update the view multiple times. Since when calling the adapter I have a method: instantiateItem called several times.

I'm trying to rewrite as follows:

private val map = HashMap<String, View>()

And after want write smth like this:

if (map.containsKey(position)
    return map.get(position)
else
//make view and add to cotnainer
val view = makeView()
container.add(view)
map.put(position, view)

But there are some difficulties how to rewrite my current method.


Solution

  • You can use getOrPut for this:

    val view = map.getOrPut(position) { makeView().also { container.addView(it) } }
    

    Or expanding out also, if you find that more readable:

    val view = map.getOrPut(position) { 
        val tmp = makeView()
        container.addView(tmp)
        tmp
    }
    

    Above is assuming you only want to call container.add on newly created views, otherwise just

    val view = map.getOrPut(position) { makeView() }
    container.addView(view)
    

    In the case of your specific code it's

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val view = map.getOrPut(position) {
            AuthorizationHeaderView(context = context)
        }
        updateViewContent(view, data[position])
        timeUpdateListeners.add(view as TimeUpdateListener)
        container.addView(view, 0)
        return view
    }