[SOLVED] Moving a View in a loop


This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under
CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

Issue

I’m trying to make my view move in a loop around 4 corners. I did it by having a keyList. Originally my view is constrained to top and left border. src=”https://i.stack.imgur.com/cZy0m.png” alt=”picture” />

After each click, I update the keylist by removing first index of keyList and move it to the last.

I have this code currently. The view moves fine for the first 4 corners (1 loop) but the app crashed after.

    var keyList = arrayListOf(1,2,3,0,1,2,3,0)

    val puckMinX = border.minX().toFloat()
    val puckMaxX = (border.maxX() - puck.width).toFloat()
    val puckMinY= border.minY().toFloat()
    val puckMaxY = (border.maxY() - puck.height).toFloat()

    fun clickTextView(view: ImageView) {
        if (keyList[0] == 0) {
            puck.x = puckMinX
            puck.y = puckMinY
            var holder =keyList[0]
            keyList.remove(holder)
            keyList+holder}
        else if (keyList[0] == 1) {
            puck.x = puckMaxX
            puck.y = puckMinY
            var holder =keyList[0]
            keyList
            keyList.remove(holder)
            keyList+holder}
        else if (keyList[0] == 2) {
            puck.x = puckMaxX
            puck.y = puckMaxY
            var holder =keyList[0]
            keyList.remove(holder)
            keyList+holder}
        else if (keyList[0] == 3) {
            puck.x = puckMinX
            puck.y = puckMaxY
            var holder =keyList[0]
            keyList.remove(holder)
             keyList+holder}
    }

    //applying lambda to each textview
    puck.setOnClickListener { clickTextView(puck) }

Could someone tell me what I did wrong? Or also is there a better way to make my view move in a loop? Any help is appreciated!

EDIT: I found the problem. My list is only removing the first index but not adding the item that’s removed back to the list. How do I update my keylist?

Solution

You can use add which adds element to end of the list

keyList.add(holder)

Edit

Note that you wont be able to print like println(keyList.add(holder)) because add will return true since it will successfully update the list. So you will have to do

keyList.add(holder)
println(keyList)

Answered By – Vojin Purić

people found this article helpful. What about you?