我如何随机化TextView的重力 - Android Eclipse

时间:2013-06-10 18:10:00

标签: java android gravity

正如标题所说我想在我的布局中随机化文本的重力(我已经能够随机化文本的颜色和文本大小) 以下代码适用于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);
                }

并且还有其他一些if和else声明,但我不认为包含它们与问题相关。

1 个答案:

答案 0 :(得分:6)

您也可以使用Random类来执行此操作。

示例:

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);
}