【问题标题】:'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference & <item element should not be here [duplicate]'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' 在空对象引用和 <item 元素不应该在这里[重复]
【发布时间】:2019-09-01 11:43:44
【问题描述】:

我试图在我的Home 活动中定义一个按钮来打开我的Settings 活动,但我得到了错误:

java.lang.RuntimeException:无法启动活动 组件信息{com.example.padmw/com.example.padmw.Home}: java.lang.NullPointerException:尝试调用虚拟方法'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' 在空对象引用上

我的设置项布局在res/menu,我尝试将它移动到res/layout,但它说元素项不应该在那里。我该怎么办?

我在 Home.class 中的按钮:

    Button mButton = (Button) findViewById(R.id.action_settings);
    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(Home.this, SettingsActivity.class));
        }
    });

我在 res/home.xml 中的项目:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
</menu>

【问题讨论】:

  • 只有当您的问题与 IDE android-studio 直接相关时,请使用 android-studio 标签。

标签: java android


【解决方案1】:

所以对于菜单项,我们是这样做的 1) 要指定活动的选项菜单,请覆盖 onCreateOptionsMenu()。在这种方法中,您可以扩充您的菜单资源:-

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.game_menu, menu);
    return true;
}

2) 处理点击事件: 您可以将此 ID 与已知菜单项进行匹配以执行适当的操作。例如:

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.action_settings:
          // do your work
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

【讨论】:

    【解决方案2】:

    如果你想使用findViewById,按钮应该在你的布局中,而不是菜单中。

    对于菜单,您需要覆盖 onOptionsItemSelected

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                // do something
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }
    

    你需要扩充 home.xml 菜单:

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.home, menu);
            return true;
        }
    

    请注意,您的 home.xml 应位于 res/menu/ 文件夹中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 2019-11-28
      相关资源
      最近更新 更多