我正在制作一个简单的应用程序来帮助我学习一些编码基础知识。用户点击ImageButton
并发生两件事:
Button
图片会变为随机图片。Button
移动到屏幕上的随机位置。我已经想出了如何孤立地完成这两件事,但是当我把它们放在onClick
中时,一次只能使用一个。
onClick
代码:
ImageButton button = (ImageButton) findViewById(R.id.my_button);
button.setOnClickListener(new OnClickListener() {
public void onClick (View v) {
// change button image
int imgNo = (int) (Math.random() * 9) + 1; // 9 images in the folder, start at index 1
int imgID = getResources().getIdentifier("chef" + imgNo, "drawable", getPackageName());
v.setBackgroundResource(imgID);
// move button to a random location
LinearLayout button_container = (LinearLayout) findViewById(R.id.my_window);
int x = (int) (Math.random() * (button_container.getWidth() - v.getWidth())); // might need to work out how to find if phone is landscape or portrait;
int y = (int) (Math.random() * (button_container.getHeight() - v.getHeight()));
v.layout(x, y, x + v.getWidth(), y + v.getHeight());
Toast.makeText(WhackachefActivity.this, "X: " + x + " Y: " + y + " Width: " + v.getWidth() + " Height: " + v.getHeight() + " Image: " + imgNo, Toast.LENGTH_LONG).show();
}
});
Toast
正好在那里证明所有变量都正常工作。如果位置更改或图像更改代码被注释掉,则另一个工作正常。如果图像随机设置为当前图像(即图像没有变化),则随机位置有效,但是否则将其设置为XML中的默认位置。
作为参考,主XML
是:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="@+id/my_window" >
<ImageButton
android:id="@+id/my_button"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:contentDescription="@string/description"
/>
作为后续行动,有两个相关问题:
答案 0 :(得分:1)
好的,对于主要问题,我没有得到一个答案 - 我不确定为什么它只是删除后台资源才会起作用,但也许如果你在布局后更改后台资源?值得一试,但这并没有真正解释为什么会发生这种情况。
现在的“奖励积分”问题,我可以回答:
1:只需拨打imageButton.performClick()
中的onCreate()
(当然,在分配OnClickListener
之后)。
2:将ImageButton
的{{1}}设置为LayoutParams
,wrap_content
,然后拨打wrap_content
。然后应调整大小以适合内容。
答案 1 :(得分:1)
我找到了一个有效的解决方案 - 使用LinearLayout的填充来移动按钮而不是使用.layout。主要活动代码(沿途有一些小的改动)现在看起来像这样:
final ImageButton button = (ImageButton) findViewById(R.id.my_button);
final LinearLayout button_container = (LinearLayout) findViewById(R.id.my_window);
button.setOnClickListener(new OnClickListener() {
public void onClick (View v) {
// change button image
int imgNo = (int) (Math.random() * 9) + 1; // 9 images in the folder, start at index 1
int imgID = getResources().getIdentifier("chef" + imgNo, "drawable", getPackageName());
button.setBackgroundResource(imgID);
button.requestLayout(); // size to fit content
// move button to a random location
int x = (int) (Math.random() * (button_container.getWidth() - button.getWidth()));
int y = (int) (Math.random() * (button_container.getHeight() - button.getHeight()));
button_container.setPadding(x, y, 0, 0);
}
});
button.performClick(); // run once at the start to set image and position randomly