If-else working, switch not

后端 未结 9 1825
一向
一向 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:27

    This is the solution. You need to use break to avoid going through each 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;
    

    I would recommend to read the oracle documentation about the switch statement.

提交回复
热议问题