繁体   English   中英

创建onClickListener时发生NullPointerException

[英]NullPointerException when creating onClickListener

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

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

有人可以看一看吗? 对于任何Android设备,我都是新手(绝望),非常感谢您的帮助。


代码(GameActivity.java):

<?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>

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解决方案,但没有取得积极的结果。

您没有在正确的视图上调用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... 就像...

... = (Button) findViewById(...);

该代码对我来说似乎很好,这告诉我您的R.java文件未更新可能存在问题。

一个快速的解决方法是转到您的AndroidManifest.xml并在某个地方键入一个空格(按空格键),然后将其保存。 如果需要,可以删除空间。 快速获得R.java文件以进行自身重建。

我以前遇到过这个问题,这就是我如何缓解它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM