我正在尝试创建一个记事本应用程序,该应用程序在顶部具有三个选项卡,每个选项卡都链接到一个不同的视图。

前两个选项卡仅包含一个要填写的表格,而第三个选项卡则是实际书写的地方。问题是,每当我尝试扩大第三个视图时,此行都会出现空指针异常:

((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语句中夸大的视图上。

09-05 18:29