android 获取menu控件空指针异常

这是我的代码:

public class MainActivity extends AppCompatActivity
{
    private static Toolbar action_add;
    private static Menu menu;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        onPrepareOptionsMenu(menu);
        action_add.setOnClickListener(new Toolbar.OnClickListener()
        {
            public void onClick(View v)
            {
                showDialog_Layout(MainActivity.this);
            }
        });
    }
    @Override
    public boolean onPrepareOptionsMenu(Menu menu)
    {
        super.onPrepareOptionsMenu(menu);
        menu.findItem(R.id.action_add).setChecked(true);
        return true;
    }
    private void showDialog_Layout(Context context) {
        LayoutInflater inflater = LayoutInflater.from(this);
        final View textEntryView = inflater.inflate(R.layout.dialoglayout, null);
        final EditText edtInput=(EditText)textEntryView.findViewById(R.id.edtInput);
        final AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setCancelable(false);
        builder.setIcon(R.drawable.a);
        builder.setTitle("Title");
        builder.setView(textEntryView);
        builder.setPositiveButton("确认",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        setTitle(edtInput.getText());
                    }
                });
        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        setTitle("");
                    }
                });
        builder.show();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }
}

这是我的错误:
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.findItem(int)' on a null object reference

onPrepareOptionsMenu(menu);
menu.findItem(R.id.action_add).setChecked(true);
两行,大神给看看呗!!!

查看全部
baidu_34589689
邓富贵儿1996
2016/05/12 16:05
  • 点赞
  • 收藏
  • 回答
    私信

2个回复