Android TableRow为null,即使它已在XML中声明
我有一个XML文件声明此TableLayout:Android TableRow为null,即使它已在XML中声明,android,nullpointerexception,tablelayout,Android,Nullpointerexception,Tablelayout,我有一个XML文件声明此TableLayout: <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="5dp" > <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content"
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/text" />
</TableRow>
</TableLayout>
然后在一些视图onClick中,我尝试这样做:
TextView nameView = new TextView(getActivity());
//sets the column to skip the first one
nameView.setLayoutParams(new TableRow.LayoutParams(i + 1));
nameView.setText(materialNames[i]);
row1.addView(nameView);
它无缘无故地抛出空指针。我使用这个完全相同的方法从XML中查找其他视图,它工作得很好,但出于某种原因,它认为这些TableRows是空的。我试着清理这个项目。你知道为什么这样不行吗?我的朋友找到了解决这个问题的办法。row1和row2变量首先在我的片段中声明为全局变量。然后在onCreateView中,我没有实际初始化它们,而是在onCreateView方法中创建了与全局变量同名的新局部变量。这是难以置信的难以找到,并修复如下:
row1 = (TableRow) view.findViewById(R.id.tableRow1);
row2 = (TableRow) view.findViewById(R.id.tableRow2);
很抱歉浪费您的时间。您是否加载了正确的片段布局?听起来它在您使用的片段布局中不存在。是的,这不是我第一次从XMLTry这样访问视图:TableRow row1=TableRow getActivity.findViewByIdR.id.tableRow1;试过了,还是空的。是不是nameView是空的?用IDE=>find用法很难找到。。。等待为什么我的作业不在名单上?或者使用调试器?但不是真的,只要看看代码,无论如何,如果您提供更多的上下文,这个问题可以很容易地解决。下次记住这一点。不要认为这是冒犯,这只是为了改进你的问题/答案
row1 = (TableRow) view.findViewById(R.id.tableRow1);
row2 = (TableRow) view.findViewById(R.id.tableRow2);