title: How do I make an ImageButton to randomly be positioned within a linear layout? (Android)
body: <p>I have a linear layout with a certain amount of padding. I want an image button to be placed randomly anywhere within that linear layout without going outside the layout. Here is my xml code:</p>
  
  <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="vertical"&gt;
  &lt;TextView
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:gravity="center"
      android:textSize="45dp"
      android:text="Text 1"
      android:id="@+id/text1" /&gt;
  &lt;TextView
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:gravity="center"
      android:textSize="30dp"
      android:text="Text 2"
      android:id="@+id/text2" /&gt;
  &lt;LinearLayout
      android:id="@+id/lay1"
      android:layout_width="match_parent"
      android:layout_height="450dp"
      android:layout_margin="20dp"&gt;
  
  &lt;ImageButton
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textSize="25dp"
      android:src="@drawable/ib"
      android:id="@+id/button1"/&gt;
  
  &lt;/LinearLayout&gt;
  &lt;/LinearLayout&gt;
  </code></pre>
  
  <p>I want the ImageButton <code>button1</code> to be placed randomly within layout <code>lay1</code>.</p>
  
  <p>I have tried getting the width and height of the layout and feeding them into a random function which I then use to provide a left margin and top margin to the imagebutton, but my app keeps crashing whenever I do that. Here's the Java code:</p>
  
  <pre><code>ImageButton b = (ImageButton) findViewById(R.id.button1);
  LinearLayout l = (LinearLayout) findViewById(R.id.lay1);
  LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) b.getLayoutParams();
  int width = l.getWidth();
  int height= l.getHeight();
  params.leftMargin = new Random().nextInt(width);
  params.topMargin = new Random().nextInt(height);
  b.setLayoutParams(params);
  </code></pre>
  
  <p>The above method did not work and my app always crashes when I open this activity. Can someone please help me out?</p>