我正在制作一个应用程序,它具有带文本的图像网格,并且每个应用程序都打开不同的活动。它工作正常,但只是为了设计目的,我想用switch statements
(我认为我可以做)取代if-else statements
,但它不起作用。现在我的工作代码来设置标签的每个图像是:If-else working,switch not
if(position == 0)
textView.setText(R.string.zero);
else if(position == 1)
textView.setText(R.string.one);
else if(position == 2)
textView.setText(R.string.two);
else if(position == 3)
textView.setText(R.string.three);
else if(position == 4)
textView.setText(R.string.four);
else if(position == 5)
textView.setText(R.string.five);
ect....
我想用:
switch(position)
case 0:
textView.setText(R.string.zero);
case 1:
textView.setText(R.string.one);
case 2:
textView.setText(R.string.two);
case 3:
textView.setText(R.string.three);
case 4:
textView.setText(R.string.four);
,但是当我这样做,永远的标签是我定义的最后一个(在我例如它将是“四”)。对于每个对象,我也有一个类似的代码,用position
变量来启动不同的intent
,但是,它会做相反的处理,并使每个意图等于第一个意图。我的语法错了,还是这不适合我的情况?
你需要'打破;'的'case'每个语句之后,否则就流下来,所以您总能获得最后的情况。 –
@SotiriosDelimanolis把它作为答案 – Blackbelt
谢谢大家!我没有意识到当你没有'return'时你需要'break'' –