I'm trying to create a "pixel" layout and manage movements over there for an exercise, and I would love to know a simple/creative way to name and use all the variables without doing terribly long lists of the same task over every "pixel", like this:
val x1y1: TextView = findViewById(R.id.x1y1)
val x2y1: TextView = findViewById(R.id.x2y1)
val x3y1: TextView = findViewById(R.id.x3y1)
val x4y1: TextView = findViewById(R.id.x4y1)
val x5y1: TextView = findViewById(R.id.x5y1)
val x6y1: TextView = findViewById(R.id.x6y1)
val x7y1: TextView = findViewById(R.id.x7y1)
val x1y2: TextView = findViewById(R.id.x1y2)
val x2y2: TextView = findViewById(R.id.x2y2)
val x3y2: TextView = findViewById(R.id.x3y2)
val x4y2: TextView = findViewById(R.id.x4y2)
val x5y2: TextView = findViewById(R.id.x5y2)
val x6y2: TextView = findViewById(R.id.x6y2)
val x7y2: TextView = findViewById(R.id.x7y2)
val x1y3: TextView = findViewById(R.id.x1y3)
val x2y3: TextView = findViewById(R.id.x2y3)
val x3y3: TextView = findViewById(R.id.x3y3)
val x4y3: TextView = findViewById(R.id.x4y3)
val x5y3: TextView = findViewById(R.id.x5y3)
val x6y3: TextView = findViewById(R.id.x6y3)
val x7y3: TextView = findViewById(R.id.x7y3)
...
I'm new here and in coding, so greetings to the community, and thanks a lot for the responses in advance!
My genius idea was doing that inside a for loop or any loop, but I haven't managed to use that.
for (i in 1..7){
for (j in 1..10){
val x$iy$j: TextView = findViewById(R.id.x1y1)
}
}
I think Kotlin doesn't allow this kind of coding, so if that's the case, are there other ways to do this, or am I condemned to do this? Also, every other way of doing this "pixel" system in Kotlin-Android is very welcome.
Never create repetitive variables like this (in any programming language). Instead, use Lists. You'll have to use the
getIdentifierfunction instead ofR.id.whatever.In this case, a 2D List (a List of Lists) seems appropriate:
Then if you want the view "x3y4", for example, you could use
textViews[2][3]to retrieve it. List indices start at 0 so we are subtracting one from those numbers in the names.However
You ought to take a step back, because also you shouldn't be creating a bunch of repetitive views in your XML layout, for the same reason you wouldn't create a bunch of repetitive variables in your code.
You should be creating these TextViews in your Kotlin code programmatically and then adding them to whatever kind of ViewGroup you had as their parent in the XML before. You can look up other questions about creating and adding views programmatically.
I should also mention, Jetpack Compose is becoming the preferred way to create UI for Android. It's completely different from how the traditional view system works, but it is more natural for this kind of thing.