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

时间:2015-10-04 08:56:50

标签: java android search settings

我是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()后,我收到错误添加&#39 ;;'`但是当我添加它时,它再次显示预期的表达式。请尽快帮助我。提前谢谢!

1 个答案:

答案 0 :(得分:0)

这是因为您正在切换案例中创建一个方法。

将方法拉出来并在内部使用,如下所示:

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);
    }
}