Answer the question
In order to leave comments, you need to log in
How to draw on the surfaceView element, which is in the layout file (one of the activity elements)?
Hello. I decided to write a relatively simple game for the android platform, but I ran into a problem. The essence of the problem is this:
1) Wherever I look - SurfaceView is created in a java file, and, one might say, completely replaces the activity (accordingly, it occupies the entire screen).
2) Since this element on the screen is not enough for me (I need to display a record, current score, etc.) - the above option for creating a SurfaceView does not suit me.
And, accordingly, the essence of the question:
How to draw in the surfaceView, which is registered in the layout file and is not created programmatically?
Answer the question
In order to leave comments, you need to log in
In the markup file, it is created as a normal element
<SurfaceView android:id="@+id/surfaceView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
Information from stackoverflow:
If the activity class uses xml markup to establish communication with the SurfaceView, for example setContentView(R.layout.main) , then the onDraw() method will be called in the SurfaceView subclass.
Benefits: Easy to scroll and zoom canvas.
Disadvantages: Every time onDraw() is called, the canvas must be completely redrawn. When drawing with a finger, it is called at an offset of each pixel. Trying to draw outside of onDraw() - see my question above.
Note: The SurfaceView subclass constructor must have an AttributeSet argument in addition to the Context argument or the application will immediately crash.
If the activity uses a SurfaceView instance to set the view, such as setContentView(new MySurfaceView(this)), the onDraw() method is not called. It is possible to obtain a canvas using the lockCanvas method and then draw it. But this is where the headache begins.
For example, what is drawn in the onSurfaceCreated() method is not saved on subsequent attempts to draw. The documentation says that you can pass a "dirty" rectangle to the lockCanvas method, outside of which pixels will be preserved between calls to lockCanvas. But it doesn't work. The "dirty" rectangle passed as an argument of type Rect will be stretched to fill the screen. (Verified by the drawRect method, which is passed the same rectangle.
And, unsurprisingly, things will be more complicated with scrolling and zooming.
Note: The example above is valid for a constructor with one argument of type Context. Here the AttributeSet is optional. If this second argument is present, NULL can be passed to it.
Thus, the setContentView() method specifies one of the approaches to drawing on the canvas.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question