【问题标题】:Cannot Find Symbol Error on Android Studio在 Android Studio 上找不到符号错误
【发布时间】:2016-07-21 17:40:35
【问题描述】:
public class MainActivity extends AppCompatActivity {

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

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
      return true;
    }

    return super.onOptionsItemSelected(item);
  }

  /**
   * Increase the score for Team A by 1 point.
   */
  public void addOneForTeamA(View v) {
    displayForTeamA(1);
  }

  /**
   * Increase the score for Team A by 2 points.
   */
  public void addTwoForTeamA(View v) {
    displayForTeamA(2);
  }

  /**
   * Increase the score for Team A by 3 points.
   */
  public void addThreeForTeamA(View v) {
    displayForTeamA(3);
  }

  /**
   * Displays the given score for Team A.
   */
  public void displayForTeamA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.team_a_score);
    scoreView.setText(String.valueOf(score));
  }
}

这是我遇到的两个错误,请帮助我解决它们。 这些代码行实际上是从 github udacity android 复制的初学者代码

错误:(21, 36) 错误:找不到符号变量菜单
错误:(33, 23) 错误:找不到符号变量 action_settings

【问题讨论】:

  • res/menu/menu_main.xml 中有 ID == action_settings 的项目吗?
  • 不,实际上我之前做过一个非常相似的代码,它工作得很好我不知道为什么我现在得到这个
  • 发生此错误是因为没有 ID == action_settings 的视图(或菜单项)。检查 res/menu/menu_main.xml 并获取正确的 ID(或共享文件 res/menu/menu_main.xml)
  • 我会用 xml 代码和正确的代码重新提出问题,请看看你是否找到了这个应用程序的解决方案
  • 谢谢大家的帮助。@Guilherme P 谢谢你的建议。刚刚删除了那些东西

标签: android


【解决方案1】:

这意味着您的资源/菜单文件夹中缺少具有 id menu 和 action_settings 的变量。

【讨论】:

    【解决方案2】:

    你有两个错误:

    getMenuInflater().inflate(R.menu.menu_main, menu);
    

    这里

    if (id == R.id.action_settings)
    

    基本上,Android Studio 不会生成 R.menu 项目...我相信 /res/menu/ 内没有文件(根据您的代码,它应该存在 /res/menu/menu_main.xml 文件。

    所以,我看到了两种可能性:

    删除菜单代码

    由于您没有 /res/menu/menu_main.xml 文件,因此您似乎没有使用菜单...所以,请从 MainActivity.java 中删除 public boolean onCreateOptionsMenu(Menu menu)public boolean onOptionsItemSelected(MenuItem item) 方法

    创建菜单文件

    如果你想使用菜单,你必须在 /res/menu/menu_main.xml 下创建一个文件并正确配置它...该文件应该至少有一个 ID 为 android:id="@+id/action_settings" 的项目

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-16
      • 1970-01-01
      • 2017-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      相关资源
      最近更新 更多