TAGS :Viewed: 6 - Published at: a few seconds ago

[ Moving a shape in Android ]

I was trying to figure out the best way to simply move a rectangle downward from the top of the screen in android because im trying to make a tetris clone but I cant figure out why android doesnt like timers. SO if you guys could help me figure out the best way to move this rectangle from top to bottom that would be awsome

in this code i created a game screen where the rectangle appears but when i try to move it with the timer it doesnt work

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

        }

       }

}
}

Answer 1


The way you use Timer is not applicable for Android. There is no such constructor like Timer(10,new TimerListener())

The fastest way to use Timer is in the snippet below:

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

    }
}, _delay, _period);