在Android中使用findViewById时为按钮获取Null
我在XML文件中创建了一个按钮,当我试图通过findViewById访问该按钮时,我遇到了NullPointer异常 按钮的Id在R.java文件中生成。但我仍然无法通过findViewById方法 Main.xml:在Android中使用findViewById时为按钮获取Null,android,nullpointerexception,android-button,Android,Nullpointerexception,Android Button,我在XML文件中创建了一个按钮,当我试图通过findViewById访问该按钮时,我遇到了NullPointer异常 按钮的Id在R.java文件中生成。但我仍然无法通过findViewById方法 Main.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.example.calendar_module.CalendarView android:id="@+id/calendar"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/NextMonth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"/>
</LinearLayout>
@文卡特
您可以清理项目、删除gen文件夹并重建应用程序。这应该可以解决这个问题
要获取id,请使用System.out.printlnNextMonth id+NextMonth.getId
如果您没有完全掌握布局和xml格式的概念,可能需要阅读更多的教程 基本上,你只需要改变这个
setContentView(R.layout.activity_main);
对此
setContentView(R.layout.Main);
其中Main是您的xml文件的实际名称以及您想要使用的布局检查按钮是否位于activity_Main.xml或其他xml中请发布activity_Main.xml您发布了Main.xml,但将ContentView设置为activity_Main.xml。那是你的problem@venkat,在这里发布您的错误我只是在Activity_main.xml中创建Hello World。没什么大不了的。
setContentView(R.layout.Main);