Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SurfaceView and error inflating class

I was trying to make an app with a custom view, and i kept getting "error inflating class". It must be that I am missing some of the basics when it comes to custom views, but I am not sure what. Here is a very simple program with a custom view, what more is needed to make it work?

(Notes: For the sake of this question, I put SurfaceView class inside of the Activity Class. This was not the situation in the larger application. I do not show the AndroidManifest.xml file here, but it is just what was generated by the wizard in eclipse.)

Here is the java:

package com.mypackage;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceView;

public class SimpleCustomViewActivity extends Activity {

class TheView extends SurfaceView{

    private static final String TAG = "TheView";

    public TheView(Context context, AttributeSet attrs) {
        super(context, attrs);
        Log.i(TAG,"TheView(" + context + "," + attrs + ")");
    }

}

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simple_layout);
        TheView v = (TheView) findViewById(R.id.myview);
    }
}

Here is file res/layout/simple_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"
    >
    <com.mypackage.SimpleCustomView.TheView
    android:id="@+id/myview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
        />
</LinearLayout>
like image 866
JimC Avatar asked Feb 23 '23 04:02

JimC


2 Answers

When u call your own surfaceView class from the xml file u need to add the following public surfaceView creating methods:

public GameView(Context context) {
    super(context);
    init(context);
}

public GameView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context);
}

public GameView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init(context);
}

If u are using the function setContentView(gv) you only need the first one.

like image 160
Carles Avatar answered Mar 07 '23 20:03

Carles


in xml it should be:

 <com.mypackage.SimpleCustomView.TheView     
    android:id="@+id/myview"     
    android:layout_width="fill_parent"     
    android:layout_height="fill_parent"> 
 </com.mypackage.SimpleCustomView.TheView>
like image 35
Lumis Avatar answered Mar 07 '23 19:03

Lumis