Reputation: 93
Screen is white & the System.out.println() within onDraw in never called.
This is my activity_main.xml
<foo.packagename.MyView
android:id="@+id/myView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
The custom view class:
public class MyView extends View {
public MyView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
System.out.println("This line is called");
while (true) {
invalidate();
}
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.GREEN);
System.out.println("This line is never printed");
}
The main activity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println("This line is called");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View myView = findViewById(R.id.myView);
}
}
Upvotes: 1
Views: 912
Reputation: 38585
invalidate()
does not cause onDraw()
to be called directly. It just tells the system that the view needs to be redrawn on the next drawing frame. Otherwise on the next drawing frame the system can use what was drawn previously since nothing has changed. In other words, your invalidate()
call and the eventual onDraw()
call are asynchronous.
Also, putting an infinite while
loop in your constructor will cause the UI thread to never execute code beyond that point, so the system will never even complete a single layout pass and your view will never be drawn even once. Needless to say, do not do this.
Upvotes: 2