Random position of TextView

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.

+4
source share
3 answers

try searching more to get a random number to stay inside the maximum width and height,

0
source

Why can't you do this?

Instead, you can find the Max x and Max y for the device, and then, based on the condition, you can set the View position to perticular.

Also see this: fooobar.com/questions/268524 / ...

may be useful to you.

comment me for any request.

0
source

but it still sometimes appears outside the viewport

  • Don't you have a name on top of your activity? It really is ... Not sure, but I think the notification bar ... If you work in full screen mode, you should have no problem.

  • Remember that xy coordinates always represent the upper left corner of an object! So after all, it may happen that you get half (or full in case: D) of your image / text / off-screen ...

0
source

All Articles