Combination of canvas and layout (Android)

My question is about Android UI. When we work with an XML layout, we write (for example)

setContentView(R.layout.main);

And when we work with 2d graphics, we write

Draw2D d = new Draw2D(this);
setContentView(d);

So what if I want to use both? I need to use layout-xml and part of the screen is fir painting (Canvas). I read about surfaceView, but what about the simple use of Canvas?

+4
source share
1 answer

In fact, you can inflate your layout from an XML file, and then get any view to draw it. SurfaceView is especially handy for drawing.

The following is an example:

main.xml:

 <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <SurfaceView android:id="@+id/surface" android:layout_width="match_parent" android:layout_height="match_parent" /> </FrameLayout> 

TestActivity.java:

 public class TestActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); SurfaceView surface = (SurfaceView) findViewById(R.id.surface); surface.getHolder().addCallback(new Callback() { @Override public void surfaceCreated(SurfaceHolder holder) { // Do some drawing when surface is ready Canvas canvas = holder.lockCanvas(); canvas.drawColor(Color.RED); holder.unlockCanvasAndPost(canvas); } @Override public void surfaceDestroyed(SurfaceHolder holder) { } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } }); } } 
+5
source

Source: https://habr.com/ru/post/1443182/


All Articles