我正在创建一个具有文本图像网格的应用程序,每个应用程序打开一个不同的活动.它工作正常,但只是为设计目的,我想取代我if-else statements与switch statements(我假设我能做到),但它不工作.现在我在每个图像上设置标签的工作代码是:
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....
Run Code Online (Sandbox Code Playgroud)
我想用:
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);
Run Code Online (Sandbox Code Playgroud)
但是当我这样做时,标签是我定义的最后一个(在我的例子中它将是"四").我也有一个类似的代码,每个对象开始intent与position变量不同但是相反,并使每个意图等于第一个.我的语法错了还是不适用于我的情况?
我有这个代码与switch我从这篇文章得到的声明,它的工作绝对正常:
String getOrdinal(final int day) {
if (day >= 11 && day <= 13) {
return "th";
}
switch (day % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我将其更改为类似下面的内容,它会中断,因为除了case 1执行之外的所有情况:
static String getOrdinal(final int day) {
StringBuilder ordinalBuilder = new StringBuilder();
ordinalBuilder.append("<sup>");
if (day >= 11 && day <= 13) {
ordinalBuilder.append("th") ;
}
switch (day % 10) {
case 1: ordinalBuilder.append("st"); …Run Code Online (Sandbox Code Playgroud)