如何在Android中移动形状?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (31)

在这段代码中,我创建了一个显示矩形的游戏屏幕,但是当我用计时器移动它时,就不工作了,要怎样才能移动呢?

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

        }

       }

}
}
提问于
用户回答回答于

使用计时器的方式不适用于Android,没有这样的构造函数Timer(10,new TimerListener())

使用计时器的最快方法是在下面的片段中:

Timer t = new Timer();
t.schedule(new TimerTask() {
    @Override
    public void run() {

    }
}, _delay, _period);

扫码关注云+社区

领取腾讯云代金券