我有一个应用程序,它有一个正方形,每 1.5 秒在屏幕上移动一次,每次单击它都会得到一个点。我试图让它在你每次点击方 block 时颜色变为随机颜色。另外,我想在设置下有一个更难模式的选项,其中方 block 每 .7 秒移动一次。
这是我的绘制方法:
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLUE);
Paint dotPaint = new Paint();
canvas.drawRect(dotX, dotY, dotX + 60, dotY + 60, dotPaint);
dotPaint.setColor(Color.WHITE);
dotPaint.setTextSize(60);
canvas.drawText("Score: " + score, 20, 60, dotPaint);
这是我的 onTouch 方法:
public boolean onTouch(View v, MotionEvent event) {
if (detectHit( (int)event.getX(), (int)event.getY() )) {
score++;
invalidate();
}
return false;
我不太确定如何在每次点击时改变正方形的颜色。
Also, here is my menu items:
public boolean onOptionsItemSelected(MenuItem item) {
// handle menu item selection
switch (item.getItemId()){
case R.id.item1:
newGame();
return true;
case R.id.item2:
quit();
return true;
case R.id.item3:
harder();
return true;
default:
return super.onOptionsItemSelected(item);
and my harder method:
public void harder(){
timer.schedule(task, 0, 700);
}
最佳答案
这只是一个建议,将您的 detectHits() 方法从 (int ... , int ...) 更改为 (MotionEvent ...) 以缩短调用时间。
对于随机颜色,您必须以编程方式生成一个。
有这个 Color.rgb(int red, int green, int blue)
方法,您可能想使用它。
所以现在你要做的是,你生成随机整数来生成颜色,就像这样
Random rnd = new Random();
Color rndCol = Color.rgb(rnd.nextInt(254), rnd.nextInt(254), rnd.nextInt(254));
现在您将应用该颜色。 首先,它不鼓励在 onDraw 期间分配对象,因此将 Paint 的分配移动到 onCreate/onResume 并使其成为进程中的一个字段。然后你将不得不像这样调整你的 onTouchMethod。
public boolean onTouch(View v, MotionEvent event) {
if (detectHit(event)) {
changeColor();
score++;
invalidate();
}
return false;
private void changeColor(){
Random rnd = new Random();
Color rndCol = Color.rgb(rnd.nextInt(254), rnd.nextInt(254), rnd.nextInt(254));
dotPaint.setColor(rndCol); // this should be a field by now and accessible from within this method
}
在将速度从 1.5 更改为 0.7 的事情中,使计时成为类中的一个字段,并在某一点减少此值以减少计时器。
由于您没有展示您当前如何每 1.5 秒移动一次正方形,因此我无法为您调整代码。
关于Java Android App 随机颜色和定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21296022/