我试图找出在android中从屏幕顶部向下移动一个矩形的最佳方法,因为我试图制作一个俄罗斯方块克隆,但我不知道为什么android不喜欢计时器。所以,如果你们能帮助我找出将这个矩形从上到下移动的最佳方法,那将是可怕的
在这段代码中,我创建了一个出现矩形的游戏屏幕,但是当我尝试用计时器移动它时它不起作用
package
com.example.coloroblind;
import java.util.Timer;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.os.Bundle;
import android.view.View;
public class GameView extends Activity {
int x=20,y=20,changeX=2,changeY=2;
boolean reverseX=false,reverseY=false;
@Override public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//setContentView(R.layout.game);
setContentView(new DrawView(this));
}
public class DrawView extends View{
public DrawView(Context context){
super(context);
}
Timer timer = new Timer(10,new TimerListener());
timer.start();
@Override public void onDraw(Canvas canvas){
super.onDraw(canvas);
//fill the screen with white
Paint paint = new Paint();
paint.setAntiAlias(true);
canvas.drawColor(Color.WHITE);
//draw a rect
paint.setColor(Color.GREEN);
RectF rect = new RectF(x,y,50,50);
canvas.drawRoundRect(rect, 6, 6, paint);
int start = ((int)Math.random())*4;
x+=changeX;
y+=changeY;
if(y>getHeight()){
changeY=-1*changeY;
reverseY=true;
}
if((reverseY==true)&&(y<0)){
reverseY=false;
changeY=-1*changeY;
}
if(x>getWidth()){
changeX=-1*(changeX);
reverseX=true;
}
if((reverseX==true)&&(x<0)){
changeX=-1*(changeX);
reverseX=false;
}
}
class TimerListener implements ActionListener{
public void actionPerformed(ActionEvent e){
repaint();
}
@Override
public void onFailure(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void onSuccess() {
// TODO Auto-generated method stub
}
}
}
}