Add AI Spinner to Player List Items

Kotlin and Android Development featuring Jetpack — by Michael Fazio (25 / 125)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Bind ViewModel to a Fragment (Pick Players) | TOC | Customize the Player List Items 👉

Given that we’re making a game here, it’d be helpful to have a way for people to play against computer-controlled players. To do that, we’re going to create some AI players, then give users the ability to choose which of those AI players they’re facing. In this part, we’re only going to worry about giving the AI players names, and we’ll leave the actual logic for Chapter 4, Update LiveData with Conditional Game Logic. We’re going to create an AI class with a number of possible AI players, then update the player items to include these AI players. Whether a user is shown a name text field for a player or the AI Spinner will depend on the state of the SwitchCompat on that player item. Before we get to the UI, let’s create the AI class.

Create the AI Class

Our AI will be another data class, this time living in the game package. For the time being, it’ll only contain one property, name, a toString method that returns that name, and a companion object with a List of AI called basicAI. In here, we’ll declare eight AI players to be used in the Spinner. The code looks like this:

​ ​package​ ​dev.mfazio.pennydrop.game​

​ ​data class​ AI(​val​ name: String) {

​ ​override​ ​fun​ ​toString​() = name

​ ​companion​…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.