I have faced the error code red line under case R.id.item ( Constant expression required ) to find the id from menu.xml and I have tried to find the problem but I was unable to find it.
MainActivity.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/black"
app:titleTextColor="@color/white"
app:title="ToolBar"
app:menu="@menu/main_menu">
</androidx.appcompat.widget.Toolbar>
</LinearLayout>
Main_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menu_item_1"
android:title="Item 1"/>
<item
android:id="@+id/menu_item_2"
android:title="Item 2"/>
</menu>
MainActivity.class
package com.example.rev_menu;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_1:
Toast.makeText(MainActivity.this, "message 1", Toast.LENGTH_SHORT).show();
case R.id.menu_item_2:
Toast.makeText(MainActivity.this, "message 2", Toast.LENGTH_SHORT).show();
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onCreatePanelMenu(int featureId, @NonNull Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
}
Where’s the exact issue?
Note: I tried ( Rebuild project, Clean project, restart the app and create new project 🙂 )
2
Answers
thanks for your information, I have tried another way if if ... but it still doesn't take any action when clicking any item from the menu :/
I don't know what is the issue ... thanks
Since Android Gradle Plugin 8.0, resource IDs are no longer
final
(see Android Gradle Plugin 8.0 changelog), and you can’t use non-final values acase
.You can either :
android.nonFinalResIds
property tofalse
in yourgradle.properties
file (not recommended),if
else if
statement as mentioned by M DEV.