why doesn't the line refresh?
LineRefresh.java:
package LineRefresh.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);
}
}
DrawView.java:
package LineRefresh.xyz.com;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
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);
开发者_如何学JAVAfinal Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
paint.setColor(Color.BLACK);
canvas.drawLine(50, 200, 270, 200, paint);
handler.postDelayed(this, 1000);
}
};
}
}
You need to call invalidate();
inside your view in order for the OnDraw method to be called again. The onDraw should look something like this:
public void onDraw( final Canvas canvas) {
paint.setColor(color);
canvas.drawLine(50, 200, 270, 200, paint);
}
Also, don't place the creation of the handler and runnable inside the onDraw method. The onDraw method will be called numerous times, whenever is needed and you don't want to create as many runnables.
In your constructor:
color = Color.Black;
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
// change color
color = color == Color.Red ? Color.Black : Color.Red;
invalidate();
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000); // You need this to call the handler for the first time
精彩评论