If-else working, switch not

后端 未结 9 1847
一向
一向 2020-12-03 14:44

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

9条回答
  •  广开言路
    2020-12-03 15:25

    You need to break; after each statement in a case, otherwise execution flows down (all cases below the one you want will also get called), so you'll always get the last case.

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

    Here's the official tutorial explaining when to and when not to use break;.

提交回复
热议问题