2010-11-25 110 views
0

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

} 
+1

offtopic:包通常命名爲喜歡com.company.product.application.class,而不是在還原prder。 – 2010-11-25 13:35:52

回答

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 
+0

我試過這個...但行不閃爍...因爲它不刷新屏幕上 – hehas 2010-11-25 14:03:18