I am trying to display a TextView at random positions on the screen, but the text should not go beyond 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:
I forgot, I had this function to get a random number within the 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 is still sometimes displayed outside the viewing area. I even subtracted 10 from each value to make sure it stays. For the most part this happens, but then it seems that it is displayed somewhere off the screen.
source share