我有一定数量的填充线性布局。我想要一个图像按钮随机放置在该线性布局内的任何位置,而不会超出布局范围。这里是我的XML代码:如何让ImageButton随机定位在线性布局中? (Android)
<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>
我想要的ImageButton button1
进行布局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);
上述方法不起作用,我的应用程序在我打开此活动时总是崩溃。有人可以帮我吗?
你说的随机是什么意思?在“屏幕上的任何位置”是随机的还是随机的,如“在n个可能的位置之一中”是随机的? – 2015-02-10 13:18:53
等待答案。我会试试看。 – GIGAMOLE 2015-02-10 13:24:53
你已经有一个宽度和高度?你可以检查你是否在那里? 如果是这样,你需要添加一个ViewTreeObserver.OnGlobalLayoutListener – SnyersK 2015-02-10 13:24:54