开发者

how do i add a timer to make the line refresh and appear after evry 2 seconds?

开发者 https://www.devze.com 2023-01-28 05:30 出处:网络
i am making an app to make the hands of a clock.That is, i draw a simple line on the screen and want it rotate like the hands of a clock.how do i do this using a timer?(so that the position of the lin

i am making an app to make the hands of a clock.That is, i draw a simple line on the screen and want it rotate like the hands of a clock.how do i do this using a timer?(so that the position of the line refreshes).Only one end point of the line should rotate,while the other remains staionary.In the folllowing code,i only draw a line on the screen:

DrawView.java:

package LineRefresh.xyz.com;

import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class DrawView extends View {
Paint paint = new Paint();

public DrawView(Context context) {
    super(context);    
}

@Override
public void onDraw(final Canvas canvas) { 
 paint.setColor(Color.BLACK);
 canvas.drawLine(50, 200, 270, 200, paint);  


}

}


LineRefresh.java:

package LineRefres开发者_如何学Goh.xyz.com;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;

public class LineRefresh extends Activity {
DrawView drawView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    drawView = new DrawView(this);
    drawView.setBackgroundColor(Color.WHITE);
    setContentView(drawView);

}
}


Try something like this:

private Handler mHandler = new Handler();

private Runnable MethodToDrawClockLine = new Runnable() 
{  
    public void run() 
    {  
        //execute here your drawing routine.
        // after drawing set the timer for another x period of time
        mHandler.postDelayed(MethodToDrawClockLine, 1000); //it'll re-execute it after 1sec.  
    }  
}

in you OnCreate or any method where you want to Start the Timer you can use:

mHandler.removeCallbacks(mUpdateTimeTask); //be sure to remove any handler before add a new one
mHandler.postDelayed(MethodToDrawClockLine, 1000); //it'll execute it after 1sec.

when you're done, remember to remove the handler. mHandler.removeCallbacks(mUpdateTimeTask);

That shold be it.

0

精彩评论

暂无评论...
验证码 换一张
取 消