因此,我正在为Android编写程序。现在,我在一个名为GraphicsView的类中,该类扩展了View并实现了View.OnClickListener。我创建了一个按钮mLeft,该按钮应该在按下时将对象移到左侧。我试图让它显示在屏幕的左下角。在我的GraphicsView构造函数中,我有以下代码:
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);
在我的onDraw中,我有:
mLeft.draw (canvas);
仅使用此代码,该程序就可以正常运行,当我进入使用GraphicsView的 Activity 时,它的运行情况非常好,除了该按钮在任何地方都没有显示。
我在构造函数中的setOnClickListener下方也有这个doe:
mLeft.setX (0);
mLeft.setY (mDisplay.getHeight () - 64);
mLeft.setHeight (64);
mLeft.setWidth (64);
mLeft.setBackgroundColor (80000000);
mLeft.setText ("<");
每当我在其中有此代码,然后转到该 Activity 时,程序就会崩溃。我的确有onClick,除了顶部的“Button mLeft”外,这是我与此按钮关联的所有代码。基本上,每当我尝试从Button调用任何这些方法时,程序似乎都崩溃了。我尝试将它们注释掉,一次在代码中只出现其中一个,所以我知道每个单独地都可以杀死该程序。
LogCat说:“12-04 15:11:03.581:I / dalvikvm(2692):找不到方法android.widget.Button.setX,该方法是从方法edu.pacificu.cs.Views.GraphicsView引用的。”
感谢您的帮助。
最佳答案
mLeft = new Button (context.getApplicationContext ());
不要那样做使用
new Button(context)
,然后仅当context
是Activity
时使用。除非您确切知道为什么要使用getApplicationContext()
,否则请不要使用。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."
正如@Selvin指出的那样,您似乎正在使用Android 2.x上不存在的方法(
setX()
)在Android 2.x上运行此应用程序。 setX()
和setY()
主要用于动画效果(例如幻灯片)。 View
的X / Y / Z位置取决于其容器(布局)和该容器的配置。
关于android - 为什么在尝试为按钮调用方法时程序崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8379380/