【问题标题】:onClick attribute in XML linking to method in Activity classXML中的onClick属性链接到Activity类中的方法
【发布时间】:2011-07-06 02:38:53
【问题描述】:

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

在我的layout.xml 中,我使用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 的类中寻找它...我不明白为什么。视图和所有仅在 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
}

在复制/粘贴此代码时,我猜问题是我使用 getApplicationContextButton 填充视图...

【问题讨论】:

  • 你能把代码贴在你使用那个布局的地方吗?

标签: android android-layout onclick


【解决方案1】:

正如我在编辑中提到的,使用 Activity 上下文更改 getApplicationContext() 可以修复它...

【讨论】:

  • 完全正确。我夸大了 XML,但它不适用于点击。将 getApplicationContext 更改为此,它可以工作!
【解决方案2】:

约定如下: 在布局 xml 文件中,您提供此属性: android:onClick:"方法名"

然后,在一个类中,你定义一个这样的方法:

public void 方法名(查看 v){ //你的方法代码 }

没有记录任何其他方法。如果您需要参数,只需在该方法中调用另一个方法即可。

【讨论】:

  • 我做的都是正确的。问题在于您应该在哪个类中定义该方法。尤其是当您使用视图充气器使用该布局时。
  • 问题是这只是一个帮手,如果这不合适你需要做的,就是通常的Button button = (Button) findViewByID(R.id.yourbutton);然后是监听器等。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-12
  • 1970-01-01
  • 2018-11-26
  • 2021-03-23
  • 1970-01-01
  • 2018-03-15
  • 1970-01-01
相关资源
最近更新 更多