Search code examples
javaandroidgravity

How can I randomize the gravity of a TextView - Android Eclipse


As the title says I want to randomize the gravity of the Text in my layout(i have allready been able to randomize the color and text size of the text) The following code is rigged to an onclicklistener :

        if (check.contains("WTF")) {
                    Random crazy = new Random();
                    display.setText("WTF!!!1!");
                    display.setTextSize(crazy.nextInt(30));
                    display.setTextColor(Color.rgb(crazy.nextInt(256),crazy.nextInt(256),crazy.nextInt(256)));
                    display.setGravity(Gravity.CENTER);
                }

and there are a couple of else if and an else statement but i don't think that including them is relevant to the question.


Solution

  • You could use Random class to do that (too).

    Example:

    int[] gravities = new int[4];
    gravities[0] = Gravity.BOTTOM;
    gravities[1] = Gravity.TOP;
    gravities[2] = Gravity.LEFT;
    gravities[3] = Gravity.RIGHT;
    
    if (check.contains("WTF")) {
        Random random = new Random();
        display.setText("WTF!!!1!");
        display.setTextSize(random .nextInt(30));
        display.setTextColor(Color.rgb(random.nextInt(256),
                                      random.nextInt(256),
                                      random.nextInt(256)));
        //from 0 to gravities.length get a random number
        int randomIndex = random.nextInt(gravities.length);
        //which will be some random gravity constant
        int randomGravity = gravities[randomIndex];
        display.setGravity(randomGravity);
    }