[英]OnClick Method is not being called
here is my code: 这是我的代码:
public class MainActivity extends Activity implements View.OnClickListener {
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button1:
Toast.makeText(getApplicationContext(), "onClick method was called", Toast.LENGTH_LONG).show();
break;
}
}
}
For some reason nothing happens and no toast shows up. 由于某种原因,什么也没发生,也没有吐司。 Did I miss anything ?
我想念什么吗? Thanks
谢谢
write: 写:
b.setOnClickListener(this);
in onCreate
: 在
onCreate
:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(this);
}
you must set a listener to the button for onClick
to work 您必须将监听器设置为按钮,才能使
onClick
起作用
As an alternative of Vipul answer you can also add the attribute onClick
in the Button
tag in the XML layout file. 作为Vipul答案的替代方法,您还可以在XML布局文件的
Button
标记中添加onClick
属性。 Example: 例:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="myMethod" />
</RelativeLayout>
And, in your MainActivity.java, remove the View.OnClickListener
implemented interface (thanks @donfuxx) add the following method: 并且,在您的MainActivity.java中,删除
View.OnClickListener
实现的接口(感谢@donfuxx),添加以下方法:
public void myMethod(View v) {
//do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.