[英]Add one click listener to two buttons, but perform different action
好吧,这是我的代码,对于仅一个按钮,我想拥有2个按钮,即btnCalcu有人可以帮助我吗? 非常感谢大家
Button btnSubmit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
btnSubmit = (Button) findViewById(R.id.button1);
btnSubmit.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(this, Home1.class);
startActivity(intent);
}
}
您可以对两个按钮使用相同的侦听器,并在单击的View
的id上使用if
语句,以了解用户单击了哪个按钮,如下所示:
@Override
public void onClick(View v) {
if(v.getId() == R.id.button1) {
// id matches submit button's id so btnSubmit clicked.
Intent intent = new Intent(this, Home1.class);
startActivity(intent);
} else if(v.getId() == R.id.button2) {
// id matches calculate button's id so btnCalcu clicked.
Intent intent = new Intent(this, OtherForm.class);
startActivity(intent);
}
}
在您的onCreate
方法中,获取第二个按钮,并将其设置为与btnSubmit
相同的方式:
btnCalcu = (Button) findViewById(R.id.button2);
btnCalcu.setOnClickListener(this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.