如何使用switch来更短地编写此代码? [英] How to write this code shorter using switch?
本文介绍了如何使用switch来更短地编写此代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
exit_app = menu.getItem(7);
exit_app.setOnMenuItemClickListener(new OnMenuItemClickListener()
{
public boolean onMenuItemClick(MenuItem clickedItem)
{
//Exit the App
try{
_run = false;
finish();
}catch(Exception c)
{
c.toString();
}
return true;
}
});
text_enter = menu.getItem(1);
text_enter.setOnMenuItemClickListener(new OnMenuItemClickListener()
{
public boolean onMenuItemClick(MenuItem clickedItem)
{
_run = false;
try{
Thread.sleep(1000);
setContentView(R.layout.text_enter);
buttonCancel.setOnClickListener(buttonSendOnClickListener);
}catch(Exception x)
{
x.toString();
}
return true;
}
});
//and so on.....
帮助.谢谢.
Help. Thanks.
推荐答案
我想我明白了你现在想做的事情.在这种情况下,我想您想要这样的东西:
I think I get what you''re trying to do now. In that case, I think you''d want something like this:
class MyClass implements OnMenuItemClickListener {
/* whatever function you're setting up the controls in */ {
/* ... */
exit_app = menu.getItem(7);
text_enter = menu.getItem(1);
/* ... */
exit_app.setOnMenuItemClickListener(this);
text_enter.setOnMenuItemClickListener(this);
/* ... */
}
public boolean onMenuItemClick(MenuItem clickedItem)
{
switch (clickedItem.getId()) {
case R.id.exit_app:
//Exit the App
try{
_run = false;
finish();
}catch(Exception c)
{
c.toString();
}
return true;
case R.id.text_enter:
_run = false;
try{
Thread.sleep(1000);
setContentView(R.layout.text_enter);
buttonCancel.setOnClickListener(buttonSendOnClickListener);
}catch(Exception x)
{
x.toString();
}
return true;
/* ... */
}
}
}
但是还有其他一些事情:menu.GetItem
中使用的数字应设为常量,例如:
But a few more things: the numbers used in menu.GetItem
should be made into constants, for example:
static final int EXIT_APP_MENU_INDEX = 7;
另外,带有开关的函数不会按原样编译,因此将需要在开关之后或默认情况下返回一个值.
Also, the function with the switch won''t compile as-is, it will need to return a value either after the switch or in a default case.
这篇关于如何使用switch来更短地编写此代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文