关于这个主题有很多问题,但找不到任何与我遇到的具体问题......
在我的 layout.xml 中,我使用 Button 的 android:onClick
标记来调用正确的 onClickListener
。我收到错误:
java.lang.IllegalStateException: Could not find a method handle_cancel(View) in the activity class com.matthieu.HelloWorldApplication for onClick handler on view class android.widget.Button with id 'button_cancel'
我在 Activity 中实现了该方法,但它正在扩展 Application
的类中寻找它...我不明白为什么。 View 和所有仅在 Activity 中设置的内容。
如果有人需要,这里是该方法的声明(在我的 Activity 中,而不是在 HelloWorldApplication 中):
public void handle_cancel(View v) {
// do something useful here
}
编辑(来自 adamp 请求)...并可能回答我自己的问题:
这是使用该布局的部分代码...
public class AddVocabularyActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.top); // that layout contains an empty LinearLayout id/main_content
}
private some_other_function() {
LinearLayout main_content = (LinearLayout) findViewById(R.id.main_content);
main_content.removeAllViews();
View.inflate(getApplicationContext(), R.layout.hello, main_content); // layout.hello is the one containing the button
}
// some other stuff
}
虽然复制/粘贴这段代码,但我猜问题出在我使用 getApplicationContext
用那个 Button
填充 View ...
最佳答案
正如我在编辑中提到的,使用 Activity 上下文更改 getApplicationContext()
可以修复它...
关于android - XML 中的 onClick 属性链接到 Activity 类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6590988/