android - XML 中的 onClick 属性链接到 Activity 类中的方法

标签 android android-layout onclick

关于这个主题有很多问题,但找不到任何与我遇到的具体问题......

在我的 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/

相关文章:

java - 关于@Override注解的问题

android - Viewpager 没有得到最后一项

android - 如果使用 Match_Constraints,嵌套约束布局不显示

javascript - onclick 事件不会在第一次点击条件语句时触发

html - 按钮在 Chrome 中不起作用

java - 在 Android 中附加两个 Mp3 文件

android - 将焦点从一个编辑文本框移到另一个

android - 如何仅在 Android 中为 TextView 的可绘制部分应用背景?

android - 处理 RelativeLayout 的更好方法

android - 如何让对话框出现在左侧?