我正在尝试使用在 Fragment 的布局findViewById()中查找一个RelativeLayout,然后将我的添加GridView到RelativeLayout. 这是我的代码:
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
GridLayout gridLayout = new GridLayout(this);
relativeLayout.addView(gridLayout);
片段布局的 XML 文件:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.sepehr.dotsandlines.Game">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/relativeLayout">
</RelativeLayout>
</FrameLayout>
错误:
原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“void android.widget.RelativeLayout.addView(android.view.View)”
注意:我在 MainActivity.java 中寻找 id 而不是 Fragment Java。