Building a Simple Tic Tac Toe Game in Android Studio
A classic noughts and crosses board is a forgiving first Android project: nine cells, two marks and a handful of rules, yet it touches layouts, event handling, application state and persistence. The game built here uses a three-by-three grid of buttons, tracks whose turn it is, announces a winner or a draw, and keeps a running score that survives closing the app. You can install the finished project on your own handset and hand it to a mate at the next barbecue.
You will work in Kotlin with Android Studio, starting from the Empty Views Activity template and finishing with a scoreboard stored locally on the device. Newcomers to Android development can read the guides on UI components and dialogs on this site first, then return to this walkthrough. Developers who learned Android with Java can translate the snippets directly, since the underlying API calls are identical.
Setting up the project and dependencies
Open Android Studio and choose New Project, then the Empty Views Activity template. Name the project TicTacToe, select Kotlin as the language and set a minimum SDK of 21, which covers essentially every active Android device sold in Australia today. Target a recent API level such as 34 or 35, because Google Play requires new listings to target a current platform API.
Add the Material Design library to your app-level build.gradle file inside the dependencies block:
implementation 'androidx.appcompat:appcompat:1.7.0'
implementation 'com.google.android.material:material:1.12.0'
Sync the Gradle project afterwards and confirm the app compiles before you add game code. Australia is one of the most Android-heavy markets in the world, with roughly 85% of active mobile devices running the platform, so a Play Store release here reaches the majority of subscribers on Telstra, Optus and Vodafone plans. Testing on a Samsung Galaxy or Google Pixel handset is more representative than relying on a single emulator.
Choosing how to draw the board
There is more than one way to place nine cells on a screen, and the choice determines how much code you write later. A few common approaches:
| Approach | How the board is built | Code you must write | Best suited to |
|---|---|---|---|
| GridLayout with nine buttons | A grid defined in XML, one button per cell | Click listeners and a marks array | Beginners and small projects |
| TableLayout with buttons | Nested rows and columns | Similar logic, more nested XML | Learners practising nested layouts |
| LinearLayout with weights | Three horizontal rows of buttons | Manual weight calculations | Simple apps without grid support |
| Custom View | One canvas drawing every cell | Touch coordinates and canvas drawing | Developers wanting full control |
| Jetpack Compose | A composable grid of cells | State holders and recomposition | Projects already using Compose |
For a first board game, a GridLayout holding nine Material buttons keeps the XML readable and the logic in plain Kotlin arrays. A custom View offers complete control over drawing but requires coordinate maths, which is a distraction while you are still learning how buttons and listeners work together.
Laying out the grid with GridLayout
Replace the content of res/layout/activity_main.xml with a vertical layout containing a status TextView, the grid and a reset button:
<androidx.gridlayout.widget.GridLayout
android:id="@+id/board"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:columnCount="3"
android:rowCount="3"
android:padding="16dp">
<com.google.android.material.button.MaterialButton
android:id="@+id/cell0"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_columnWeight="1"
android:layout_rowWeight="1"
android:text="" />
</androidx.gridlayout.widget.GridLayout>
Repeat the button element for cell1 through cell8, changing only the android:id value. Setting each cell to 0dp width and height and pairing it with column and row weights makes every square grow evenly, so the board fills the screen on a tall handset or in landscape without hard-coded sizes. Use dp for all measurements so the layout scales with the density of the display.
Because the board sits inside a scroll-free vertical container, keep the padding modest and let the cells take the remaining space. Sydney commuters checking their phones on a Metro train and Melbourne passengers riding the tram both benefit from a board that stays visible in portrait orientation without scrolling.
Wiring up taps and turn tracking
Store the game state in plain fields rather than reading the button labels back later. An integer array marks each square as empty, X or O, while a second array holds references to the nine buttons:
private val marks = IntArray(9)
private val cells = arrayOfNulls<MaterialButton>(9)
private var currentPlayer = 1
private var moves = 0
Attach one shared listener to every cell in onCreate. When a button is tapped, ignore it if the square is already taken, write the mark into the array, update the button text and disable it so a double tap cannot overwrite a move:
cell.setOnClickListener {
val index = cells.indexOf(cell)
if (marks[index] != 0) return@setOnClickListener
marks[index] = currentPlayer
cell.text = if (currentPlayer == 1) "X" else "O"
cell.isEnabled = false
moves++
checkResult()
currentPlayer = if (currentPlayer == 1) 2 else 1
status.text = if (currentPlayer == 1) "X to play" else "O to play"
}
Disabling a cell immediately is the simplest guard against input arriving faster than your logic can process it.
Detecting wins, draws and saving the score
A win is any row, column or diagonal that carries three identical marks. List the eight possible lines once and scan them after every move:
private fun winningLines() = listOf(
intArrayOf(0, 1, 2), intArrayOf(3, 4, 5), intArrayOf(6, 7, 8),
intArrayOf(0, 3, 6), intArrayOf(1, 4, 7), intArrayOf(2, 5, 8),
intArrayOf(0, 4, 8), intArrayOf(2, 4, 6)
)
If every line fails and the move counter reaches nine, the game is a draw. Save the score with SharedPreferences, writing the value whenever a player wins:
val prefs = getSharedPreferences("scores", MODE_PRIVATE)
val wins = prefs.getInt("wins", 0)
prefs.edit().putInt("wins", wins + 1).apply()
SharedPreferences suits a single counter perfectly. Reach for SQLite or Room only when you add match history, timestamps or player names. If you later add a daily bonus, remember that Australian daylight saving shifts the reset boundary between standard and daylight time, so calculate the day against a local time zone rather than a fixed offset.
Styling the board for bright screens
Give each cell a background drawable with rounded corners and a contrasting stroke, then define colours in res/values/colors.xml. A restrained palette of white and charcoal with a single accent colour reads clearly in strong summer light, which matters when the phone is held on a beach in December. Support dark mode through res/values-night/ so the board remains comfortable during a night match or a long cricket session.
Accessibility deserves attention from the beginning. Set a contentDescription on every button describing the square, such as "Row 2, column 3, empty", and update it as marks appear so TalkBack announces the move. Large text settings should still fit an X or O inside the cell, which is another reason to avoid fixed text sizes and to test at the smallest supported screen dimensions.
Keep the app fully offline. It suits the Australian habit of sharing an unlimited data plan with a household group, and it avoids collecting personal information that would fall under the Australian Privacy Principles and the Privacy Act 1988.
Recommendations for a reliable build
- Keep the rules in a separate method or small model class, so the winning logic can be unit tested without inflating a button on screen.
- Disable each cell the moment it receives a mark, preventing duplicate taps from corrupting the turn order.
- Describe every square with a content description and announce results through the status TextView for TalkBack users.
- Store the score in SharedPreferences and move to a Room database only when you need match history.
- Confirm a reset with an AlertDialog, so a stray tap cannot wipe a game in progress.
- Test on a physical handset connected to an Australian mobile network alongside an emulator running a recent Android version.
- Release through Google Play with a small package size, since local installs are dominated by Android devices and offline play keeps the app light on data.