コーディングの基礎を学ぶのに役立つ簡単なアプリを作成しています。ユーザーが をクリックするImageButton
と、次の 2 つのことが起こります。
Button
画像がランダム画像に変わります。- が画面上の
Button
ランダムな位置に移動します。
これらの両方を個別に行う方法を理解しましたが、両方を一緒にすると、onClick
一度に 1 つしか機能しません。
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"
/>
フォローアップとして、2 つの関連する質問:
- アプリが最初にロードされたときに onClick コードを 1 回実行するにはどうすればよいですか?
- ImageButton 自体のサイズを自動的に作成するにはどうすればよいですか (つまり、ランダムな画像のサイズを引き伸ばすことなく、わずかに異なるサイズに合わせることができます)。