4

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.

Jacob Sánchez
  • 390
  • 3
  • 15
Kris B
  • 3,436
  • 9
  • 64
  • 106

3 Answers3

0

try looking up abit more on getting the random number to stay inside the max width and height,

steven
  • 71
  • 2
  • 9
  • Actually, it helped a little, because I forgot had a function to get a random number within a range. Updated my OP with it. – Kris B Nov 26 '12 at 02:25
0

Why cant you do this?

Instead of doing that, you can found the Max x and Max y for the device and then Based on condition you can set the View's position to perticular position.

Also see this: SO

might be helpful to you.

comment me for any query.

Community
  • 1
  • 1
Shreyash Mahajan
  • 23,386
  • 35
  • 116
  • 188
0

but it still sometimes displays outside the viewing area

  1. Dont you have title on top of your activity? That does count in... Am not sure but I think the notification bar as well... If u work in fullscreen mode, you shouldnt have problem.

  2. Remember that the x y coordinates are always the upper left corner of an objectview! So it still can be happen that u get half (or full in case :D) of your picture/textview/whatever outside the screen...

David Toth
  • 85
  • 9