Android phone

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.

        <string-array name="months">


In the res > values > strings.xml lets set the text label for the button to make it easy to change.

`<?xml version="1.0" encoding="utf-8"?>
    <string name="app_name">RandomMonth</string>
    <string name="button_text">Push Me!</string>
    <string name="text1"></string>


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.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android=""
            android:id = "@+id/text1"
            android:text="@array/months"    />
            android:onClick="pushMe" />

In our main activity, we’ll set the logic for the random month, color, and button behavior. For the color we’ll be using

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().

    public class RandomMonthActivity extends Activity
        Button btn;    

        protected void onCreate(Bundle b)
            btn = (Button) findViewById(; // Create button
            final String months[] = getResources().getStringArray(R.array.months);
            final TextView tv =(TextView)findViewById(;

            btn.setOnClickListener(new View.OnClickListener()
                public void onClick(View v)
                    int random = (int) (Math.random() * months.length);
                    Random myColor = new Random();
                    tv.setTextColor(Color.rgb(myColor.nextInt(255), myColor.nextInt(255), myColor.nextInt(255))); // randomly pick a color
                    tv.setText(months[random]); // set a random month

If you have any questions or comment, please post them below. If you liked this post, you can share it with your followers or follow me on Twitter!