How can i get a smooth move using timertask?

被刻印的时光 ゝ 提交于 2019-12-25 02:08:22

问题


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); 

回答1:


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 .




回答2:


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 !!



来源:https://stackoverflow.com/questions/8135416/how-can-i-get-a-smooth-move-using-timertask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!