16 May 2015

Amazing Random Class Variables



Playing Android Games is an amazing experience as every time one plays the game, s/he comes across new obstacles, new villains of different sizes, different colors, different numbers, new backgrounds and much more. This feature retains the interest of the player in the game by preventing the boredom which is created when the player plays the games which loads the same components every time.

This amazing feature is achieved with the help of Random class variables. These variables generate random values restricted to the limit specified every time they are executed.

Let us learn the use of Random class variables with simple example. Let us create an Android application which will generate random colors in the 3 x 3 grid every time the “Play” button is pressed.

Code:

package com.example.randomcolorsgenerator;

import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.View;
import android.widget.*;

public class MainActivity extends Activity {

TextView t[] = new TextView [9];
Button b1;
int i,red,green,blue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        t[0] = (TextView)findViewById(R.id.tv1);
        t[1] = (TextView)findViewById(R.id.tv2);
        t[2] = (TextView)findViewById(R.id.tv3);
        t[3] = (TextView)findViewById(R.id.tv4);
        t[4] = (TextView)findViewById(R.id.tv5);
        t[5] = (TextView)findViewById(R.id.tv6);
        t[6] = (TextView)findViewById(R.id.tv7);
        t[7] = (TextView)findViewById(R.id.tv8);
        t[8] = (TextView)findViewById(R.id.tv9);
        b1 = (Button)findViewById(R.id.button);
   
            b1.setOnClickListener(new View.OnClickListener() {
               
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    try{
                    Random r = new Random();
                    for(i=0;i<9;i++){
                        red = r.nextInt(256);
                        green = r.nextInt(256);
                        blue = r.nextInt(256);
                        t[i].setBackgroundColor(Color.rgb(red,green,blue));
                        t[i].setText(red+","+green+","+blue);
                    }
                    }
                   
                    catch(Exception e){}
                }
           
            });
  
    }
   
}

Layout file:


Snapshots:


No comments:

Post a Comment