一定量のパディングがある線形レイアウトがあります。レイアウトの外に出ることなく、その線形レイアウト内の任意の場所に画像ボタンをランダムに配置したい。ここに私のxmlコードがあります:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<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" />
<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" />
<LinearLayout
android:id="@+id/lay1"
android:layout_width="match_parent"
android:layout_height="450dp"
android:layout_margin="20dp">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:src="@drawable/ib"
android:id="@+id/button1"/>
</LinearLayout>
</LinearLayout>
ImageButtonbutton1
を layout 内にランダムに配置したいlay1
。
レイアウトの幅と高さを取得してランダム関数に入力しようとしましたが、これを使用して画像ボタンに左マージンと上マージンを提供しましたが、それを行うたびにアプリがクラッシュし続けます。Javaコードは次のとおりです。
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);
上記の方法は機能せず、このアクティビティを開くとアプリが常にクラッシュします。誰かが私を助けてくれますか?