How to extend 'TextView' by two properties with the use of 'Tag'?

Viewed 53

I try to program a game with 12 coins in Android/Kotlin. The coins are made by a TextView and created at runtime. All works fine so far.

   fun createCoin(coinNumber: Int) : TextView {
    val createdCoin = AppCompatTextView(this)

    createdCoin.background = ContextCompat.getDrawable(this, R.drawable.simple_circle)
    createdCoin.gravity = Gravity.CENTER
    createdCoin.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT)
    createdCoin.text = (coinNumber +1).toString()
    createdCoin.textSize = 20F
    createdCoin.setTextColor(Color.BLACK)
    createdCoin.tag = ??????

    return createdCoin
}

But now I need to save 2 more informations with each coin.

  1. posIndex:Int
  2. state:coinState

The enum:

    enum class coinState{
    UNKNOWN,
    TRUE,
    FALSE,
    Up,
    DOWN
}

Is there a possibility to store these two informations in an object/class and assign it to the tag in TextView. Or is there another simple way?

Thanks for your help Jan

3 Answers

Way to save 2 object without any effort and additional classes :

tag = Pair(5, coinState.DOWN)

There is a simple way. You can concatenate strings with a special delimeter, and then just read it as array of params by splitting by delimeter.

You can also use Pair like in answer above. In case if there are no parameters more than 2.

Or you can create own model

data class CoinParams(var name1: Type1, var name2: Type2, ....)
createdCoin.tag = CoinParams(1, "Some value", ...)
val params: CoinParams = createdCoin.tag as CoinParams

Example of string:

createdCoin.tag = "$value1||$value2"
params = createdCoin.tag.split("||")
 tex.tag=Triple("x",3,5)
      var tagLogin=  loginAsTv.tag as Triple<String,Int,Int>
        println("tag ${tagLogin.first}")

You can try this.. or You ca set it on the basis of pattern

eg tag= position_coinindex
Related