设置菜单项文本

Set menu item text

我在设置菜单项文本时遇到问题。我想在启动 activity 时查看购物篮中所有商品的价格。但是每当我开始购物清单 activity 时,我都会收到以下错误:

java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.findItem(int)' on a null object reference

这是代码:

    public class Shopping_list_activity extends AppCompatActivity{

    private Menu menu;

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

            updateMenuTitles();
    }

     @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_shopping_list, menu);
        this.menu = menu;
        return true;
    }

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.menu_shopping_list_saveList) {
            Toast.makeText(Shopping_list_activity.this, " Clicked", Toast.LENGTH_SHORT).show();
        }
//        else if (id == R.id.menu_shopping_list_total){
//          Toast.makeText(Shopping_list_activity.this, getPriceOfDisplayedItems() + " total", Toast.LENGTH_SHORT).show();
//        }

        return super.onOptionsItemSelected(item);
    }

private void updateMenuTitles() {
    MenuItem menuItem = menu.findItem(R.id.menu_shopping_list_total);
    if (getPriceOfDisplayedItems() > 0) {
        menuItem.setTitle(String.valueOf(getPriceOfDisplayedItems()));
    } else {
        menuItem.setTitle("Total: 0.00");
    }
}

getPriceOfDisplayedItems() 显示正确的价格。

和 XML 文件:

    <?xml version="1.0" encoding="utf-8"?>
<menu 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">

    <item
        android:id="@+id/menu_shopping_list_total"
        android:title="@string/total"
        app:showAsAction="always" />

</menu>

谁能帮我解决这个问题?

您应该在 xml 中添加 menu_shopping_list_saveList 项目:

<?xml version="1.0" encoding="utf-8"?>
<menu 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">

    <item
        android:id="@+id/menu_shopping_list_total"
        android:title="@string/total"
        app:showAsAction="always" />
    <item
        android:id="@+id/menu_shopping_list_saveList"
        android:title="@string/total"
        app:showAsAction="always" />

</menu>

我认为 onCreate 方法在 onCreateOptions 菜单之前被调用。这就是 this.menunull 的原因。尝试将 updateMenuTitles 的调用移动到 onCreateOptionsMenu