本文介绍了Android的:使用setOnClickListener /的onClick switch语句超过1按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们说我有几个按钮中的LinearLayout,其中2个是:
mycards_button =((按钮)this.findViewById(R.id.Button_MyCards));
exit_button =((按钮)this.findViewById(R.id.Button_Exit));
我注册 setOnClickListener()
他们两个:
mycards_button.setOnClickListener(本);
exit_button.setOnClickListener(本);
我如何切换到的onclick?
中的两个按钮区别 公共无效的onClick(视图v){
开关(?????){
案件 ???:
/ **开始一个新的活动MyCards.java * /
意向意图=新意图(这一点,MyCards.class);
this.startActivity(意向);
打破;
案件 ???:
/ ** AlerDialog当点击退出* /
MyAlertDialog();
打破;
}
解决方案
使用:
公共无效的onClick(视图v){ 开关(v.getId()){ 案例R.id.Button_MyCards:/ **开始一个新的活动MyCards.java * /
意向意图=新意图(这一点,MyCards.class);
this.startActivity(意向);
打破; 案例R.id.Button_Exit:/ ** AlerDialog当点击退出* /
MyAlertDialog();
打破;
}
}
请注意,这将不会在Android的库项目工作(由于http://tools.android.com/tips/non-constant-fields)在这里你将需要使用这样的:
INT ID = view.getId();
如果(ID == R.id.Button_MyCards){
动作1();
}否则如果(ID == R.id.Button_Exit){
动作2();
}
Let's say I have a few buttons in a LinearLayout, 2 of them are:
mycards_button = ((Button)this.findViewById(R.id.Button_MyCards));
exit_button = ((Button)this.findViewById(R.id.Button_Exit));
I register setOnClickListener()
on both of them:
mycards_button.setOnClickListener(this);
exit_button.setOnClickListener(this);
How do I make a SWITCH to differentiate between the two buttons within the Onclick ?
public void onClick(View v) {
switch(?????){
case ???:
/** Start a new Activity MyCards.java */
Intent intent = new Intent(this, MyCards.class);
this.startActivity(intent);
break;
case ???:
/** AlerDialog when click on Exit */
MyAlertDialog();
break;
}
解决方案
Use:
public void onClick(View v) {
switch(v.getId()){
case R.id.Button_MyCards: /** Start a new Activity MyCards.java */
Intent intent = new Intent(this, MyCards.class);
this.startActivity(intent);
break;
case R.id.Button_Exit: /** AlerDialog when click on Exit */
MyAlertDialog();
break;
}
}
Note that this will not work in Android library projects (due to http://tools.android.com/tips/non-constant-fields) where you will need to use something like:
int id = view.getId();
if (id == R.id.Button_MyCards) {
action1();
} else if (id == R.id.Button_Exit) {
action2();
}
这篇关于Android的:使用setOnClickListener /的onClick switch语句超过1按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!