[英]Null pointer exception when calling addView(): Android
我正在嘗試創建一個記事本應用程序,該應用程序在頂部具有三個選項卡,每個選項卡都鏈接到一個不同的視圖。
前兩個選項卡僅包含一個要填寫的表格,而第三個選項卡則是實際書寫的地方。 問題是,每當我嘗試擴大第三個視圖時,此行都會出現空指針異常:
((LinearLayout) findViewById(R.id.drawRoot)).addView(v,0);
這是我的代碼:
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, show the tab contents in the container
Fragment fragment = new Section3Fragment();
Bundle args = new Bundle();
args.putInt(Section3Fragment.ARG_SECTION_NUMBER, tab.getPosition() + 1);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container3, fragment)
.commit();
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class Section3Fragment extends Fragment {
public Section3Fragment() {
}
int section;
public static final String ARG_SECTION_NUMBER = "section_number";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
section = args.getInt(ARG_SECTION_NUMBER);
View view;
if (section == 1)
{
view = inflater.inflate(R.layout.section3_page1, container,false);
return view;
}
if (section == 2){
view = inflater.inflate(R.layout.section3_page2, container, false);
return view;
}
else {
if(v != null)
Log.v("not null", "not null");
view = inflater.inflate(R.layout.section3_page3, container, false);
((LinearLayout) findViewById(R.id.drawRoot)).addView(v,0); //null pointer exception here!!
return view;
}
}
}
對象v是我用來進行實際繪制的類的實例。
和section3_page3布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawRoot"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
非常感謝您對此問題的見解。
乍一看,您是否要這樣做:
((LinearLayout) view.findViewById(R.id.drawRoot)).addView(v,0);
您正在尋找片段的視圖。 不在if語句中誇大的視圖上。
您發布了section3_page3.xml,但打開了inflater.inflate(R.layout.section3_page2, container, false)
。 這是拼寫錯誤還是問題的根本原因?
打開錯誤的XML文件將導致findViewById()在此處返回null:
view = inflater.inflate(R.layout.section3_page2, container, false);
((LinearLayout) findViewById(R.id.drawRoot)).addView(v,0);
因此,NullPointerException ...我猜你的意思是:
view = inflater.inflate(R.layout.section3_page3, container, false);
((LinearLayout) findViewById(R.id.drawRoot)).addView(v,0);
由於您使用的是ActionBar和Fragments,因此建議您更改以下內容:
((LinearLayout) findViewById(R.id.drawRoot)).addView(v,0);
到這個:
((LinearLayout) getActivity().findViewById(R.id.drawRoot)).addView(v,0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.