So, I’m writing a program for Android. Right now, I’m in a class called GraphicsView, which extends View and implements View.OnClickListener. I have created a button mLeft, that is supposed to move an object to the left when pressed. I am trying to get this to display on the bottom left of the screen. In my constructor for GraphicsView I have the code:
mLeft = new Button (context.getApplicationContext ());
mLeft.setId (1); // wasn't sure what else to set for an id, I only did that to see if it would fix anything
mLeft.setOnClickListener (this);
And in my onDraw I have:
mLeft.draw (canvas);
With just this code, the program runs fine, and when I go to the activity that uses GraphicsView it works totally fine, except for the face that the button doesn’t show up anywhere.
I also have this doe in my constructor, right below the setOnClickListener:
mLeft.setX (0);
mLeft.setY (mDisplay.getHeight () - 64);
mLeft.setHeight (64);
mLeft.setWidth (64);
mLeft.setBackgroundColor (80000000);
mLeft.setText ("<");
Whenever I have this code in there, and I go to that activity, the program crashes. I do have onClick in there, and other than “Button mLeft” at the top, this is all of the code I have associated with this button. Basically, it looks like the program is crashing whenever I try to call any of those methods from Button. I have tried commenting these out to there there is only one of them present in the code at a time, so I know that each of them individually could kill the program.
The LogCat says: “12-04 15:11:03.581: I/dalvikvm(2692): Could not find method android.widget.Button.setX, referenced from method edu.pacificu.cs.Views.GraphicsView.”
Thank you for your help.
Don’t do that. Use
new Button(context), and then only ifcontextis anActivity. Never usegetApplicationContext()unless you know exactly why you are using it.As @Selvin points out, you appear to be running this application on Android 2.x, using a method (
setX()) that does not exist on Android 2.x.setX()andsetY()are mostly for animation effects (e.g., slides). The X/Y/Z position of yourViewis determined by its container (layout) and that container’s configuration.