leighboz
leighboz

Reputation: 148

runtime InflateException when trying to use a Custom View in xml layout

I've been reading a lot of similar questions to try and find the solution for this but with no luck.

MainActivity.java

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.game);
}

game.xml

<RelativeLayout 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" >
<View
    android:id="@+id/adView"
    android:background="@drawable/ad"
    android:layout_width="320dp"
    android:layout_height="50dp"
    />

<my.package.MainGamePanel
    android:id="@+id/gameView"        
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    /> </RelativeLayout>

MainGamePanel.java

public class MainGamePanel extends SurfaceView implements SurfaceHolder.Callback {

private MainThread thread;

public MainGamePanel(Context context, AttributeSet a) {
    super(context, a);
    View.inflate(context, R.layout.game, null);
    onFinishInflate();
    thread = new MainThread(getHolder(), this);
    setFocusable(true);
    thread.setRunning(true);

etc. etc.

And then outside the MainGamePanel constructor is the function:

@Override
protected void onFinishInflate() {
    getHolder().addCallback(this);
}

There is also a MainThread.java file but I don't think that is the problem.

This is the runtime exception:

java.lang.RuntimeException: Unable to start activity ComponentInfo{my.package/my.package.MainActivity}: android.view.InflateException: Binary XML file line #13: Error inflating class my.package.MainGamePanel

If I change the setContentView in MainActivity to setContentView(new MainGamePanel(this)) and remove the AttributeSet parameter from the constructor, and delete the View.Inflate(context, R.layout.game, null); , then it works, but I want to figure out how to use the custom view in the xml file.

Upvotes: 2

Views: 288

Answers (1)

toadzky
toadzky

Reputation: 3846

it looks like you are circularly inflating layouts. you setContentView on R.layout.game, which contains a MainGamePanel, which inflates R.layout.game, which contains a MainGamePanel, etc.

you should take the View.inflate line out of the onCreate method. It's not doing anything anyway, as far as I can see. you also shouldn't explicitly call onFinishInflate. That will be called automatically when the inflation of the MainGamePanel instance is actually finished.

Upvotes: 2

Related Questions