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);
final 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);
}
};
}
}
答案 0 :(得分:0)
您需要在视图中调用invalidate();
才能再次调用OnDraw方法。 onDraw看起来像这样:
public void onDraw( final Canvas canvas) {
paint.setColor(color);
canvas.drawLine(50, 200, 270, 200, paint);
}
另外,不要在onDraw方法中创建处理程序和runnable。 onDraw方法将在需要时多次调用,并且您不希望创建尽可能多的runnable。
在你的构造函数中:
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