switch case statement error: case expressions must be constant expression

后端 未结 9 1357
予麋鹿
予麋鹿 2020-12-04 07:51

My switch-case statement works perfectly fine yesterday. But when I run the code earlier this morning eclipse gave me an error underlining the case statements in color red a

相关标签:
9条回答
  • 2020-12-04 08:28

    R.id.*, since ADT 14 are not more declared as final static int so you can not use in switch case construct. You could use if else clause instead.

    0 讨论(0)
  • 2020-12-04 08:32

    How about this other solution to keep the nice switch instead of an if-else:

    private enum LayoutElement {
        NONE(-1),
        PLAY_BUTTON(R.id.playbtn),
        STOP_BUTTON(R.id.stopbtn),
        MENU_BUTTON(R.id.btnmenu);
    
        private static class _ {
            static SparseArray<LayoutElement> elements = new SparseArray<LayoutElement>();
        }
    
        LayoutElement(int id) {
            _.elements.put(id, this);
        }
    
        public static LayoutElement from(View view) {
            return _.elements.get(view.getId(), NONE);
        }
    
    }
    

    So in your code you can do this:

    public void onClick(View src) {
        switch(LayoutElement.from(src)) {
        case PLAY_BUTTTON:
            checkwificonnection();
            break;
    
        case STOP_BUTTON:
            Log.d(TAG, "onClick: stopping srvice");
            Playbutton.setImageResource(R.drawable.playbtn1);
            Playbutton.setVisibility(0); //visible
            Stopbutton.setVisibility(4); //invisible
            stopService(new Intent(RakistaRadio.this,myservice.class));
            clearstatusbar();
            timer.cancel();
            Title.setText(" ");
            Artist.setText(" ");
            break;
    
        case MENU_BUTTON:
            openOptionsMenu();
            break;
        }
    }
    

    Enums are static so this will have very limited impact. The only window for concern would be the double lookup involved (first on the internal SparseArray and later on the switch table)

    That said, this enum can also be utilised to fetch the items in a fluent manner, if needed by keeping a reference to the id... but that's a story for some other time.

    0 讨论(0)
  • 2020-12-04 08:35

    Solution can be done be this way:

    1. Just assign the value to Integer
    2. Make variable to final

    Example:

    public static final int cameraRequestCode = 999;
    

    Hope this will help you.

    0 讨论(0)
提交回复
热议问题