【发布时间】:2015-03-06 23:12:01
【问题描述】:
当我单击“开始时间”按钮时,它有时会完全移出屏幕,这很糟糕。而且,对我来说,按钮的放置不够随机,有时只需单击一下,它就会向下移动一点。最后,应用程序没有得到时间,而是以空指针停止。 Button 应该留在屏幕上,点击时随机放置在新位置,点击几下后,我想收到经过的时间。为什么这不起作用?
代码:
@Override
public void onClick(View v) {
Button b = (Button) findViewById(R.id.start_time);
Random r = new Random();
View decorView = getWindow().getDecorView();
int screenWidth = decorView.getWidth();
int screenHeight = decorView.getHeight();
long startTime = SystemClock.elapsedRealtime();
i++;
/*
Random r = new Random();
int x = r.nextInt(R.id.wrap_content);
int y = r.nextInt(R.id.wrap_content);
b.setX(x);
b.setY(y);
*/
if (i == 1 ) {
start_time.setX(r.nextInt(screenWidth - start_time.getWidth()));
start_time.setY(r.nextInt(screenHeight - start_time.getHeight()));
}
if (i == 2 ) {
start_time.setX(r.nextInt(screenWidth - start_time.getWidth()));
start_time.setY(r.nextInt(screenHeight - start_time.getHeight()));
}
if (i == 3 ) {
start_time.setX(r.nextInt(screenWidth - start_time.getWidth()));
start_time.setY(r.nextInt(screenHeight - start_time.getHeight()));
}
if (i == 4 ) {
start_time.setX(r.nextInt(screenWidth - start_time.getWidth()));
start_time.setY(r.nextInt(screenHeight - start_time.getHeight()));
}
if (i == 5 ) {
start_time.setX(r.nextInt(screenWidth - start_time.getWidth()));
start_time.setY(r.nextInt(screenHeight - start_time.getHeight()));
}
if (i == 6 ) {
start_time.setX(r.nextInt(screenWidth - start_time.getWidth()));
start_time.setY(r.nextInt(screenHeight - start_time.getHeight()));
}
else if (i == 7) {
long difference = SystemClock.elapsedRealtime() - startTime;
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",difference);
// Toast.makeText(getApplicationContext(), getIntent().getStringExtra("time"), Toast.LENGTH_LONG).show();
textview1.setText(getIntent().getStringExtra("time"));
finish();
}
}
和xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="chdfss.dsfwegg.trhhGame" >
<Button
android:id="@+id/start_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="139dp"
android:text="Button" />
</RelativeLayout>
【问题讨论】:
-
请解释为什么您使用 3 种不同的方式来生成随机位置
-
第一次是我自己的自制软件。第二次屏幕边缘不是按钮的边框。在今晚的最新研究之后,我现在将以我认为最简单的方式来做这件事
标签: java android button random time