If-else working, switch not

2019-01-12 00:02发布

I am making an app that has a grid of images with text and each one opens a different activity. It works fine but just for design purposes I want to replace my if-else statements with switch statements (which I assume I can do) however it doesn't work. Right now my working code to set the label on each image is:

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....

I want to use:

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);    

but when I did that ever label was the last one that I defined (in my example it would be "four"). I also have a similar code for each object to start a different intent with the position variable however that does the opposite and makes every intent equal to the first one. Is my syntax wrong or will this not work for my situation?

9条回答
Melony?
2楼-- · 2019-01-12 00:27

You need to use break statement after eace case operations. In a switch-case statement if you dont use a break statement then all the cases after that specific one will be executed also

case 0:
   textView.setText(R.string.zero);    
   break;
查看更多
混吃等死
3楼-- · 2019-01-12 00:29

Don't forget to put break; after each case: like that:

switch(position){
case 0:
   textView.setText(R.string.zero);    
   break;
case 1:
   textView.setText(R.string.one);
   break;
case 2:
   textView.setText(R.string.two);    
   break;
case 3:
   textView.setText(R.string.three);
   break;
case 4:
   textView.setText(R.string.four);  
   break;
}
查看更多
Rolldiameter
4楼-- · 2019-01-12 00:35

Using a break statement after each case should fix the problem. I would also use a default statement as well after the last case.

查看更多
登录 后发表回答