Error: constant expression required Android Studio

huangapple go评论65阅读模式
英文:

Error: constant expression required Android Studio

问题

It seems like you're encountering an error related to the R.id statements in your Java code. The issue is likely due to the fact that you have extra asterisks around R.id.home, R.id.favorites, and R.id.status. You should remove the asterisks so that these lines look like this:

case R.id.home:
    getSupportFragmentManager().beginTransaction().replace(R.id.container, homeFragment).commit();
    return true;

case R.id.favorites:
    getSupportFragmentManager().beginTransaction().replace(R.id.container, favoritesFragment).commit();
    return true;

case R.id.tools:
    getSupportFragmentManager().beginTransaction().replace(R.id.container, toolsFragment).commit();
    return true;

case R.id.status:
    getSupportFragmentManager().beginTransaction().replace(R.id.container, statusFragment).commit();
    return true;

After making this change, the error should be resolved, and your code should work as expected.

英文:

So i am trying to code a bottom navigationbar in java in Android Studio and i keep getting the Error: constant expression required. The bold R.id. statements below are what causing the error.
Here is my Code of the MainActivity:

package com.rpitest.appmudu;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.MenuItem;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationBarView;

public class MainActivity extends AppCompatActivity {

    BottomNavigationView bottomNavigationView;

    HomeFragment homeFragment = new HomeFragment();
    FavoritesFragment favoritesFragment = new FavoritesFragment();
    ToolsFragment toolsFragment = new ToolsFragment();
    StatusFragment statusFragment = new StatusFragment();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bottomNavigationView = findViewById(R.id.bottom_navigation);

        getSupportFragmentManager().beginTransaction().replace(R.id.container,homeFragment).commit();

        bottomNavigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                switch (item.getItemId()){
                    case **R.id.home:**
                       getSupportFragmentManager().beginTransaction().replace(R.id.container,homeFragment).commit();
                       return true;

                    case **R.id.favorites**:
                       getSupportFragmentManager().beginTransaction().replace(R.id.container,favoritesFragment).commit();
                       return true;

                    case **R.id.tools**:
                       getSupportFragmentManager().beginTransaction().replace(R.id.container,toolsFragment).commit();
                       return true;

                    case** R.id.status**:
                        getSupportFragmentManager().beginTransaction().replace(R.id.container,statusFragment).commit();
                        return true;

                }
               return false;



            }
        });
    }
}

and that is my code from the menu directory:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/home"
        android:title="Home"
        android:icon="@drawable/icon_home"/>

    <item android:id="@+id/favorites"
        android:title="favorites"
        android:icon="@drawable/icon_favorites"/>

    <item android:id="@+id/tools"
        android:title="Tools"
        android:icon="@drawable/icon_tools"/>

    <item android:id="@+id/status"
        android:title="Status"
        android:icon="@drawable/icon_status"/>
</menu>

I do not know what I am doing wrong.

I really have no idea whats wrong with the code.

答案1

得分: 1

Here is the translated code snippet:

如果您正在使用DrawerLayout和NavigationView并且遇到需要常量表达式的问题请尝试以下代码它可以正常工作请使用If() else-if()代替Switch() Case

drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
navigationView = findViewById(R.id.navigationview);

navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
    @SuppressLint("NonConstantResourceId")
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        int id = menuItem.getItemId();
        if (id == R.id.home_menu) {
            Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
            return true;
        } else if (id == R.id.profile_menu) {
            Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
            return true;
        }
    }
});

Note: I've translated the code as requested, but please make sure to review it in the context of your project to ensure it meets your requirements.

英文:

if you are using DrawerLayout & NavigationView and you are facing the constant expression required issue then try the below code its worked properly. Use If() else-if() instead of Switch() Case.

  drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
    navigationView = findViewById(R.id.navigationview);

    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
    @SuppressLint("NonConstantResourceId")
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
            int id = menuItem.getItemId();
            if(id == R.id.home_menu){
                Intent intent = new Intent(HomeActivity.this,LoginActivity.class);
                startActivity(intent);
                finish();
                return true;
            }
            else if(id == R.id.profile_menu) {
                Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
                return true;

            }  }  });

答案2

得分: 0

以下是翻译后的代码部分:

为什么不这样做

    Map<Integer, Fragment> fragments = new HashMap<>();
    fragments.put(R.id.home, homeFragment);
    fragments.put(R.id.favorites, favoritesFragment);
    fragments.put(R.id.tools, toolsFragment);
    fragments.put(R.id.status, statusFragment);

    public boolean onNavigationItemSelected(MenuItem item) {
        Fragment fragment = fragments.get(item.getItemId());
        if (fragment != null) {
            getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, fragment)
                .commit();
            return true;
        }
        return false;
    }

我没有看到您的其他代码所以不确定创建地图的最佳位置在哪里但它只需要在片段对象之后创建

在较新版本的Java中您甚至可以在单个表达式中创建地图但我不知道Android是否支持这样做。)

请注意,这是您提供的代码的翻译版本。如果您需要任何其他帮助或有其他问题,请随时告诉我。

英文:

Why not something like:

Map&lt;Integer, Fragment&gt; fragments = new HashMap&lt;&gt;();
fragments.put(R.id.home, homeFragment);
fragments.put(R.id.favorites, favoritesFragment);
fragments.put(R.id.tools, toolsFragment);
fragments.put(R.id.status, statusFragment);

public boolean onNavigationItemSelected(MenuItem item) {
    Fragment fragment = fragments.get(item.getItemId());
    if (fragment != null) {
        getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, fragment)
            .commit();
        return true;
    }
    return false;
}

I haven't seen the rest of your code so I'm not sure where the best place to create the map would be, but it just needs to be after the fragment objects.

(In newer versions of Java you could even create the map in a single expression, but I don't know if Android supports that.)

答案3

得分: 0

这个错误可能发生在R.class无法正确映射ID时。尝试在你的gradle.properties中添加以下两行:

android.nonTransitiveRClass=false
android.nonFinalResIds=false
英文:

This error may happen when R.class has trouble mapping the IDs. Try adding the following two lines in your gradle.properties

android.nonTransitiveRClass=false
android.nonFinalResIds=false

huangapple
  • 本文由 发表于 2023年5月26日 00:36:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76334499.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定