在 MainyActivity.java 中设置搜索和设置代码时出错

Error in setting Search and Settings code in MainyActivity.java

我是 Android Studio 的新手。我正在通过 developer.android.com 学习编程。我正在添加操作栏,但现在我遇到了错误。

`

@Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle presses on the action bar items
            switch (item.getItemId()) {
                case R.id.action_search:
                    private void  openSearch() {
                    Toast.makeText(this, "Search button pressed", Toast.LENGTH_SHORT).show();
                }


                    return true;
                case R.id.action_settings:
                    private void  openSettings()  {
                    startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
                }
                    return true;
                default:
                    return super.onOptionsItemSelected(item);
            }
        }

这是我的代码,在 openSearch()openSettings() 之后,我在添加 ';' 时遇到错误,但是当我添加它时,它再次显示预期的表达式。请尽快帮助我。提前致谢!

这是因为您正在 switch case 中创建方法。

把方法拉出来,直接在里面用,像这样:

private void  openSearch() {
    Toast.makeText(this, "Search button pressed", Toast.LENGTH_SHORT).show();
}

private void  openSettings()  {
    startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    switch (item.getItemId()) {
        case R.id.action_search:
            openSearch();
            return true;
        case R.id.action_settings:
            openSettings();
        return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}