我正在尝试创建一个记事本应用,顶部有三个标签,每个标签链接到不同的视图。
前两个标签将只包含一个表格来填写,而第三个标签将是实际写作完成的地方。问题是每当我试图试图给第三个视图充气时,我会得到这一行的空指针异常:
((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>
非常感谢对此问题的任何见解。
答案 0 :(得分:2)
快速浏览一下,你想做什么:
((LinearLayout) view.findViewById(R.id.drawRoot)).addView(v,0);
您正在寻找片段的视图。而不是你在if语句中夸大的观点。
答案 1 :(得分:1)
您发布了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);
答案 2 :(得分:1)
由于你正在使用ActionBar和Fragments,我建议你改变它:
((LinearLayout) findViewById(R.id.drawRoot)).addView(v,0);
进入这个:
((LinearLayout) getActivity().findViewById(R.id.drawRoot)).addView(v,0);