본문 바로가기

명사 美 비격식 (무리 중에서) 아주 뛰어난[눈에 띄는] 사람[것]

IDE/Android Studio

switch문 Constant expression required, R.id 오류

switch문을 if else문으로 바꾸자.

 

 if-else 문에서는 
조건식으로 평가하는 값의 타입이 제한되지 않기 때문에 
변수나 리턴값 등 런타임에 결정되는 값도 사용할 수 있다.

 

쉽게 switch보단 덜 까다롭다고 하겠다.

 

 

도움이 되고자 수정 전/후 코드를 첨부한다.

@Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                switch (item.getItemId()) {
                    case R.id.tab1:
                        Toast.makeText(getApplicationContext(), "첫 번째 탭 선택됨", Toast.LENGTH_LONG).show();
                        getSupportFragmentManager().beginTransaction()
                                .replace(R.id.container, fragment1).commit();
                        return true;
                    case R.id.tab2:
                        Toast.makeText(getApplicationContext(), "두 번째 탭 선택됨", Toast.LENGTH_LONG).show();
                        getSupportFragmentManager().beginTransaction()
                                .replace(R.id.container, fragment2).commit();
                        return true;
                    case R.id.tab3:
                        Toast.makeText(getApplicationContext(), "세 번째 탭 선택됨", Toast.LENGTH_LONG).show();
                        getSupportFragmentManager().beginTransaction()
                                .replace(R.id.container, fragment3).commit();
                        return true;
                }
                return false;
            }
@Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                int itemId = item.getItemId();

                if (itemId == R.id.tab1) {
                    Toast.makeText(getApplicationContext(), "첫 번째 탭 선택됨", Toast.LENGTH_LONG).show();
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.container, fragment1).commit();
                    return true;
                } else if (itemId == R.id.tab2) {
                    Toast.makeText(getApplicationContext(), "두 번째 탭 선택됨", Toast.LENGTH_LONG).show();
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.container, fragment2).commit();
                    return true;
                } else if (itemId == R.id.tab3) {
                    Toast.makeText(getApplicationContext(), "세 번째 탭 선택됨", Toast.LENGTH_LONG).show();
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.container, fragment3).commit();
                    return true;
                }
                return false;
            }