Shon Otmazgin
Shon Otmazgin

Reputation: 23

How to add buttons on camera preview

I'm new on Android, and i trying to build a camera app. I build an Camera Preview which extends SurfaceView and implements SurfaceHolder.Callback for previewing the camera on the Camera Activity. here is the contractor :

public CameraPreview(Context context) {
    super(context);
    mContext = context;
    mStartRequested = false;
    mSurfaceAvailable = false;
    mCamera = null;
    mHolder = getHolder();
    mHolder.addCallback(this);
}

and the onCreate(in CameraActivity.java) method which initialize the layout:

@Override
protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.activity_camera);
    mPreview = new CameraPreview(this);
    FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
    preview.addView(mPreview);
}

and finally the Layout XML :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<FrameLayout
    android:id="@+id/camera_preview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button"
        android:layout_gravity="center_horizontal|bottom" />
</FrameLayout>
</LinearLayout>

AndroidMainifest.xml:

<application
    ...
    android:theme="@android:style/Theme.Holo.Light.NoActionBar.Fullscreen" >

As you can see i tried to add a button on the camera preview but i cant see the button when the app is lunching. can anyone see the mistake??

Thanks you !

Upvotes: 1

Views: 3583

Answers (1)

greeble31
greeble31

Reputation: 5042

The preview is probably on top of the button (in the Z-order). This line:

preview.addView(mPreview);

adds the CameraPreview to the end of the FrameLayout's internal list of child views. A FrameLayout renders its child views in order; as such, the preview is being drawn after the button, or "over" it. Try this instead:

preview.addView(mPreview, 0);

You can also order your CameraPreview by having it inflate from the XML instead, by using a tag with the fully qualified class name, like this:

<com.yourdomain.CameraPreview
.../>

...although you will need to override the View(Context context, AttributeSet attrs); constructor to make that work.

Upvotes: 4

Related Questions