In this application we are going to display the 12 months of the year at random, in different colors when the user presses a button. This example shows you how to use a button, how to use an array as a resource, and how to use random colors (this is done in Java).
We are going to break this up in a few pieces. The months will be stored in a string array in xml. The button and a TextView to display the months will be created in the layout xml file.
Finally we’ll tie everything together and do the logic for randomizing the months and colors in the main activity.
Create a string array xml
Create a file called string_array.xml inside of res > values. This file will contain a resources tag that holds our string-array and each month will be stored in an item tag.
In the res > values > strings.xml lets set the text label for the button to make it easy to change.
The layout will be pretty straightforward. We are going to use a TextView as a container to store the colored month text. The button will pull it’s label text from strings.xml and will reference an onClick method that we’ll write in our activity.
In our main activity, we’ll set the logic for the random month, color, and button behavior. For the color we’ll be using android.graphics.color.
For example, color.rgb(int r, int g, int b) which is a static method that uses values 0-255 for colors.
To choose the colors and month we’ll use Math.random().