将xml文件添加/扩展到另一个xml
时出错我正在尝试将xml文件添加到另一个xml,但是在添加/膨胀时我收到了错误。
我的主要xml是
item_non_highlight.xml
<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="10"
android:baselineAligned="false">
<LinearLayout android:id="@+id/column_big"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="5"
android:orientation="vertical"
/>
<LinearLayout android:id="@+id/column_small"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="5"
android:orientation="vertical"
/>
这段代码显示我的错误
View v = inflater.inflate(R.layout.item_non_highlight, null);
LinearLayout column_highlight = (LinearLayout) v.findViewById(R.id.column_big);
v = setupHighlightViewTablet(column_highlight);
private View setupHighlightViewTablet(View parentView) {
int itemCount = 1;
LinearLayout columnOdd = (LinearLayout) parentView.
findViewById(R.id.social_media_column_one); // this two layouts belongs to a different xml
LinearLayout columnEven = (LinearLayout) parentView.
findViewById(R.id.social_media_column_two); //
View itemView = inflater.inflate(R.layout.highlight, null);
if (itemCount % 2 == 0) {
columnEven.addView(itemView);
} else {
columnOdd.addView(itemView); // error at this ine
}
}
itemCount++;
return parentView;
}
错误是
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.addView(android.view.View)' on a null object reference
由于
答案 0 :(得分:0)
尝试使用false flag将您的布局充气为第3个参数:
View v = inflater.inflate(R.layout.item_non_highlight, null, false);
你得到例外,因为默认情况下android会尝试将新增加的视图添加到它的父级(第二个参数),当你传递null时,你会得到提及的异常。
查看此文档: http://developer.android.com/reference/android/view/LayoutInflater.html#inflate(org.xmlpull.v1.XmlPullParser,android.view.ViewGroup,boolean)