java - 创建 onClickListener 时出现 NullPointerException

标签 java android xml

好的,我已经创建了一个非常基本的 Android 游戏。简单的思路就是当用户点击跳转按钮时,调用跳转方法。我正在使用 XML 文件来声明按钮,但我发现它会抛出 NullPointerException。

我查看了其他答案,我意识到最可能的原因是因为按钮 ID 不在 XML 文件中(至少在它被初始化时)。我已尝试更改我的代码以匹配此处的其他答案,但它仍然抛出异常。

谁能看一眼就知道了?我对任何 Android 都是新手(而且毫无希望),非常感谢您的帮助。


代码(GameActivity.java):

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
theView = (GameView)findViewById(R.id.gameView);
//Create jump button and link to jump event
    Button jumpButton = (Button)theView.findViewById(R.id.jumpbutton);
    jumpButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
        //jump             
        theGame.getPlayer().jump();
        }
    });

XML(main.xml):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent">

<com.RoundHouse.GoGoRunner.GameView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/gameView"/>

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/jumpbutton"
        android:layout_marginRight="0dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true" android:clickable="true" android:background="@drawable/jumpbutton"/>
</RelativeLayout>

再次抱歉,我问了一个看似微不足道的问题,但我已经尝试了其他 Stack Overflow 解决方案,但没有取得积极成果。

最佳答案

您没有在右 View 上调用 Button 实例化。

<com.RoundHouse.GoGoRunner.GameView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/gameView"/>

<Button...

正如您在上方看到的那样,按钮不在 GameView 中,而您正在此处寻找按钮...

setContentView(R.layout.main);
theView = (GameView)findViewById(R.id.gameView);
//Create jump button and link to jump event
Button jumpButton = (Button)theView.findViewById(R.id.jumpbutton);

您获得 GameView 并在其上调用 findView...。就这样调用它吧......

... =(按钮)findViewById(...);

关于java - 创建 onClickListener 时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28531785/

相关文章:

java - 如何在并发客户端之间广播消息?

java - 我试图手动计算两个日期之间的天数差异

java - 从数据库查询中过滤值

java - `javax.imageio.ImageIO` 是否需要文件锁定?

android - 使用Android的相机拍摄灰度照片2

java - XMLConstants.FEATURE_SECURE_PROCESSING 无法禁用

java - 在自定义 Unity Android 插件上调用非静态方法

android - 如何在 Intellij Idea CE 中导入 Android 库?

xml - Xstream错误

ios - XML 解析以获取链接,在 Objective-C 中