我有一个活动,有一个按钮,我想按下按钮来烘烤一些东西,我这样做:
public class myActivity extends Activity implements OnClickListener {
EditText nameEditText;
Button okButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nameEditText = (EditText) findViewById(R.id.editText);
okButton = (Button) findViewById(R.id.button);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button:
Toast.makeText(myActivity.this, "Pressed", Toast.LENGTH_LONG)
.show();
break;
default:
break;
}
}
}
哪里错了?
谢谢
答案 0 :(得分:4)
你忘记设置按钮的监听器
因为您的活动已在实施onClickListener
界面,因此您必须在okButton.setOnClickListener(this);
功能okButton = (Button) findViewById(R.id.button);
之后放置onCreate
。请检查以下代码:
public class myActivity extends Activity implements OnClickListener {
EditText nameEditText;
Button okButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nameEditText = (EditText) findViewById(R.id.editText);
okButton = (Button) findViewById(R.id.button);
okButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button:
Toast.makeText(myActivity.this, "Pressed", Toast.LENGTH_LONG)
.show();
break;
default:
break;
}
}
}
答案 1 :(得分:2)
你必须添加一个寄存器
okButton.setOnClickListener(this);
之后
okButton = (Button) findViewById(R.id.button);
答案 2 :(得分:0)
您缺少okButton = setOnClickListenre(this)
,因为您的活动在点击侦听器上实现。在okButton = (Button) findViewById(R.id.button);