0

I used following code to move a image it works fine but while moving the image not perform a smooth moving. Can anyone find the problem in my code?

 handler = new Handler(); 
    t = new Timer(); 
    t.scheduleAtFixedRate(new TimerTask() { 
            public void run() { 
                    handler.post(new Runnable() { 
                            public void run() { 

                                if(left<=400){

                                 left=left+1;

                                     RelativeLayout.LayoutParams rp = new RelativeLayout.LayoutParams(
                                                new ViewGroup.MarginLayoutParams(
                                                        RelativeLayout.LayoutParams.WRAP_CONTENT,
                                                        RelativeLayout.LayoutParams.WRAP_CONTENT));
                                                 rp.setMargins(left, top, 0, 0);
                                                 Train.setLayoutParams(rp);

                                }else{
                                    Toast.makeText(getApplicationContext(), "Toast completed", Toast.LENGTH_SHORT).show();
                                t.cancel();
                                }

                            } 
                    }); 

            } 

    }, 0,30); 
VSC
  • 272
  • 3
  • 12

2 Answers2

4

TimerTask and Threads are not good choice for consistent UI changes.

  1. Create CustomView by entending SurfaceView .

  2. Manage some class variables for position of views.

  3. In onDraw() create view and update variables for next positioning .

  4. Wherever want to refresh manually, call invalidate.

Follow this tutorial for more help .

Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191
Shailendra Singh Rajawat
  • 8,172
  • 3
  • 35
  • 40
  • I am try onDraw() method but result is same.public void onDraw(Canvas canvas){ if(mX – VSC Nov 17 '11 at 04:02
  • 1
    you should not call invalidate(); inside onDraw() because it will leads to a cyclic frequent refreshing() ; call invalidate from outside the class wherever you need to do so . to read some tutorials first will be much beneficial . – Shailendra Singh Rajawat Nov 17 '11 at 06:05
0
ImageView img_animation = (ImageView) findViewById(R.id.imageView1);

    TranslateAnimation animation = new TranslateAnimation(0.0f, 400.0f,0.0f, 0.0f);          //  new TranslateAnimation(xFrom,xTo, yFrom,yTo)
    animation.setDuration(5000);  // animation duration 
    animation.setRepeatCount(5);  // animation repeat count
    animation.setRepeatMode(2);   // repeat animation (left to right, right to left )
    //animation.setFillAfter(true);      

    img_animation.startAnimation(animation); 

Animation is the best smooth moving !! Try it !!