Search code examples
androidandroid-layoutgridviewviewandroid-custom-view

Getting an error when trying to create my own view class?


Hey guys I am getting an error when trying to create view in my MainActivity. Below I have provided a small bit of my code from my custom GridView and Activity. For some reason when I am trying to pass in the parameters into the GridView in the OnCreate in the MainActivity I am getting the following error in Eclipse:

The constructor GridView(this, Cell[][]) is undefined

But in my GridView Class I am clearly providing a constructor like this. Not sure what the problem is. I am even declaring additional constructors because someone had suggested that but no luck. Am I declaring the context correct or is there something I need to do on the XML side? Can someone please tell what I am doing wrong? Thanks

Custom GridView layout:

public class GridView extends View {

    Context context;
    private Cell[][] grid; //Cell class - is an interface

    //constructors
    public GridView (Context context){
        super(context);
    }

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

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


    public GridView(Context context, Cell[][] grid) {
        super(context);
        this.context = context;
        this.grid = grid;
        //...more stuff
    }
    //...more stuff
}

Main activity:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width = size.x;
    int height = size.y;

    Cell[][] grid = new Cell[height][width];
    final GridView view = new GridView(this, grid);

    //...more stuff

}
//...more stuff 

}


Solution

  • I think your problem is that you are using a class name that is already implemented in Android (android.widget.GridView), so when you call the constructor of the class, compiler may be confused between them.

    Either rename your implementation to a name unique to the system (MyGridView for e.g.) or specifically call your class name including your package name (Your.Namespace.GridView)