I'm trying to display a TextView
in random positions on the screen, but the text shouldn't go outside the screen. The text will always be short, no more than 3 words. This is what I have so far:
final TextView tv = ((TextView)findViewById(R.id.text);
final Random rand = new Random();
final DisplayMetrics metrics = getResources().getDisplayMetrics();
int width = rand.nextInt(metrics.widthPixels);
int height = rand.nextInt(metrics.heightPixels);
final FrameLayout.LayoutParams flp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
flp.setMargins(width, height, 0, 0);
tv.setLayoutParams(flp);
UPDATE:
Forgot, I had this function to get a random number within a range:
public static int Random(final int lower, final int uppper)
{
return lower + (int)(Math.random() * ((uppper - lower) + 1));
}
So I updated the code to this:
int width = Random(0, metrics.widthPixels);
int height = Random(0, metrics.heightPixels);
But it still sometimes displays outside the viewing area. I even subtracted 10 from each value, to ensure it stays in. For the most part it does, but then it seems like it shows somewhere outside the screen.