我的工作代码是

@Override
    public boolean onMenuItemSelected(int featureId, MenuItem item)
    {
        Toast tst;

        if (item.getItemId() == R.id.menuVada) {
            tst = Toast.makeText(Main.this, " Vada ", 2000);

        } else {
            tst = Toast.makeText(Main.this, "Menu Title: " + item.getTitle()
                    + " Menu ID: " + item.getItemId(), 2000);
        }
        tst.setGravity(Gravity.CENTER, 0, 0);
        tst.show();

        return true;

    }

但这段代码不起作用
@Override
    public boolean onMenuItemSelected(int featureId, MenuItem item)
    {
        Toast tst;

        if (item.getItemId() == R.id.menuVada) {
            //tst = Toast.makeText(Main.this, " Vada ", 2000);

        } else {
            tst = Toast.makeText(Main.this, "Menu Title: " + item.getTitle()
                    + " Menu ID: " + item.getItemId(), 2000);
        }
        tst.setGravity(Gravity.CENTER, 0, 0);
        tst.show();

        return true;

    }

为什么不工作我的代码?

请帮忙。

此致

最佳答案

如果 (item.getItemId() == R.id.menuVada) 呢?

只需将 tst 初始化为 null 。然后检查 tst!=null 是否显示 toast

@Override
    public boolean onMenuItemSelected(int featureId, MenuItem item)
    {
        Toast tst = null;

        if (item.getItemId() == R.id.menuVada) {
            //tst = Toast.makeText(Main.this, " Vada ", 2000);

        } else {
            tst = Toast.makeText(Main.this, "Menu Title: " + item.getTitle()
                    + " Menu ID: " + item.getItemId(), 2000);
        }
        if(tst!=null){
            tst.setGravity(Gravity.CENTER, 0, 0);
            tst.show();
        }

        return true;

    }

关于Android - 局部变量 tst 可能尚未初始化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7472408/

10-10 19:54