无法创建CustomSurfaceView

时间:2015-10-08 08:52:36

标签: android xml surfaceview

我有一个CustomSurfaceView。我不能在我的应用程序中创建它。什么问题?我创建了所有构造,并且不知道为什么我有错误膨胀类。这是我的代码:

public class CustomSurfaceView extends SurfaceView implements SurfaceHolder.Callback {

SurfaceHolder mHolder;
Camera mCamera;

CustomSurfaceView(Context context)
{
    super(context);

    init();
}
CustomSurfaceView(Context context, AttributeSet attributeSet)
{
    super(context, attributeSet);

    init();
}
CustomSurfaceView(Context context, AttributeSet attributeSet, int defStyle)
{
    super(context, attributeSet, defStyle);

    init();
}

public void init()
{
    mHolder = getHolder();
    mHolder.addCallback(this);

    mCamera = Camera.open();
}

public void surfaceCreated(SurfaceHolder holder)
{
    try {
        mCamera.setPreviewDisplay(holder);
        mCamera.startPreview();
    }catch (IOException e)
    {
        e.printStackTrace();
    }
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h )
{
    if (mHolder.getSurface() == null)
    {
        return;
    }


    try{
        mCamera.stopPreview();
    }catch (Exception e) {

    }


    try {
        mCamera.setPreviewDisplay(holder);
        mCamera.startPreview();
    }catch (IOException e)
    {
        e.printStackTrace();
    }

}
public void surfaceDestroyed(SurfaceHolder holder)
{
    if (mHolder.getSurface() == null)
    {
        return;
    }


    try{
        mCamera.stopPreview();
    }catch (Exception e) {

    }

    mCamera = null;
}
}

我尝试在XML文件中创建此视图。这是XML:

<LinearLayout 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" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".mainActivity"
android:orientation="vertical">


<com.example.orientationsensor.CustomSurfaceView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:name = "com.example.orientationsensor.CustomSurfaceView"/>

创建时出错。 Android Studio给我这个错误:

  

java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.orientationsensor / com.example.orientationsensor.mainActivity}:android.view.InflateException:二进制XML文件行#32:错误膨胀类CustomSurfaceView

1 个答案:

答案 0 :(得分:0)

好的,我解决了这个问题。我应该在值中创建attrs.xml并写下:

<declare-styleable name="CustomSurfaceView">

</declare-styleable>

还需要将contsructor的隐私更改为公开