Junior — Middle
Kuidas rakendada maleplaadi kuvamist programmis?
sobes.tech AI
Vastus AI-lt
To display a chessboard in an Android application, you can use GridLayout with 8 columns and 8 rows, where each cell is a View (for example, ImageView or Button). The colors of the cells alternate to create a classic chess pattern.
Example:
val gridLayout = GridLayout(context).apply {
rowCount = 8
columnCount = 8
}
for (row in 0 until 8) {
for (col in 0 until 8) {
val cell = View(context).apply {
val isBlack = (row + col) % 2 == 1
setBackgroundColor(if (isBlack) Color.DKGRAY else Color.LTGRAY)
layoutParams = GridLayout.LayoutParams().apply {
width = 100
height = 100
}
}
gridLayout.addView(cell)
}
}
You can also use Canvas for custom drawing of the board if more flexibility and animation are needed. In that case, override the onDraw method and draw squares using drawRect.
It is important to ensure size adaptability and the ability to display figures over the board.