Android:为什么我不能在onCreate方法之外的按钮上调用setOnClickListener方法? [英] Android: why can't I call setOnClickListener method on a button outside of an onCreate method?

查看:370
本文介绍了Android:为什么我不能在onCreate方法之外的按钮上调用setOnClickListener方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个新手问题,但为什么我不能在onCreate方法之外的按钮上调用setOnClickListener方法?

This is a newbie question but why can't I call setOnClickListener method on a button outside of an onCreate method?

例如为什么我不能这样做?或者Eclipse可能没有onCreate方法之外的setOnClickListener代码提示?因为没有显示任何内容。

For example why can't I do this? Or maybe Eclipse just don't have setOnClickListener code hinting outside of onCreate method? Cause nothing shows up.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);
}


Button button = (Button) findViewById(R.id.button_send);
   button.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {
      // Do something in response to button click
  }
});


推荐答案

您可以在任何函数中使用setonclicklistener。但这不是你的确切问题。
实际问题是

You can setonclicklistener in any function. But this is not your exact problem. Actual problem is

setContentView(R.layout.main_layout);

您可以在 setContentView 之后调用 findViewById 功能。 setContentView 用于设置活动的布局。您的布局包含不同的视图,如按钮等。因此,如果您不设置布局,则无法使用findViewById访问您的视图,如果您无法访问,则无法使用它们。

you can call findViewById function after setContentView. setContentView is used to set layout on an activity. Your layout contains different views like buttons etc. So if you will not set your layout then you cannot access your views by using findViewById and if you cannot access then you cannot use them.

正确的顺序是:

1 Set layout on your activity using setContentView.
2 Find id for your view using findViewById.
3 Then use your views for your purposes.

始终专注于基础知识。

还有一个问题是你在任何函数之外调用setOnClickListener。在任何函数静态块之外,仅允许函数声明和赋值。下面的陈述既不是他们。因此它永远不会执行,并且永远不会发生回调。

One more problem is you are calling setOnClickListener outside any function. Outside any function static blocks, function declaration and assignments are only allowed. Below statement is neither of them. So it will never execute and callback will never occur.

button.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {
      // Do something in response to button click
  }

});

这篇关于Android:为什么我不能在onCreate方法之外的按钮上调用setOnClickListener方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆