rickyoswald
rickyoswald

Reputation: 48

Custom view in xml layout not working

I'm trying to add a subclass of View to my activity_main.xml like this.

However, the device and emulator drop out of the app straight away. The error appears to be Error inflating class com.example.androidtest.PuzzleView

<?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.example.androidtestapp.PuzzleView
    android:id="@+id/puzzleView"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="60"/>

<include
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="40"
    layout="@layout/activity_input"/>

</LinearLayout>

and

package com.example.androidtestapp;


public class PuzzleView extends View {


public PuzzleView(Context context) {
    super(context);
    setFocusable(true);
    setFocusableInTouchMode(true);


}
}

Upvotes: 1

Views: 1333

Answers (1)

Iain_b
Iain_b

Reputation: 1053

I think the problem is you need to have a constructor with AttributeSet attrs as a parameter

public PuzzleView(Context context, AttributeSet attrs) {
    super(context, attrs);
    //code
}

Upvotes: 2

Related Questions