user1752669
user1752669

Reputation: 63

Combine Canvas and layout (Android)

My question about Android UI. When we work with 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 a part of a screen is fir painting (Canvas). I read about surfaceView, but what about simple using Canvas?

Upvotes: 6

Views: 17149

Answers (1)

sdabet
sdabet

Reputation: 18670

You can actually inflate your layout from an XML file and then retrieve any view to draw on it. SurfaceView are especially convenient for drawing.

You can find below 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) {
        }
    });
}
}

Upvotes: 9

Related Questions