在动态添加片段中的视图时出现NullPointerException

时间:2014-08-14 07:47:30

标签: android android-layout android-fragments

我正在尝试动态地将TableLayout添加到片段内的LinearLayout中。

以下代码:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState){
        View rootview = inflater.inflate(R.layout.dashboard_fragment, container, false);
        dash_board = (LinearLayout) rootview.findViewById(R.layout.dashboard_fragment);
        table = new TableLayout(getActivity());
        TableRow tr_header = new TableRow(getActivity());
        TextView Name = new TextView(getActivity());

        Name.setText("Name");
        LayoutParams Name_params =  new LayoutParams();
        Name_params.width= 100;

        Name.setLayoutParams(Name_params);
        Name.setPadding(2, 0, 2, 2);

        tr_header.addView(Name);

        TextView Points = new TextView(getActivity());

        Points.setText("Points");
        LayoutParams point_params =  new LayoutParams();
        point_params.width= 100;

        Points.setLayoutParams(point_params);
        Points.setPadding(2, 0, 2, 2);

        tr_header.addView(Points);

        table.addView(tr_header);

        dash_board.addView(table);

        return rootview;
    }

但是在将仪表板添加到仪表板布局(dash_board.addView(table);)时,我得到的是NullPointerException

问题是什么?

2 个答案:

答案 0 :(得分:1)

实际上在rootView中没有dashboard_fragment作为ViewGroup,因为rootView是一个非常明显的dashboard_fragment作为ViewGroup。所以这两行代码是异常的原因:

  

查看rootview =   inflater.inflate(R.layout.dashboard_fragment,container,false);

     

dash_board =   (的LinearLayout)rootview.findViewById(R.layout.dashboard_fragment);

如果您这样做,实际上逻辑是正确的:

  

查看rootview =   inflater.inflate(R.layout.dashboard_fragment,container,false);

     

dash_board =   (LinearLayout)rootView;

这是此过程最简单的形式:

  

dash_board   =(LinearLayout)inflater.inflate(R.layout.dashboard_fragment,container,false);

答案 1 :(得分:0)

而不是这个

View rootview = inflater.inflate(R.layout.dashboard_fragment, container, false);
    dash_board = (LinearLayout) rootview.findViewById(R.layout.dashboard_fragment);

应该是

LinearLayout dash_board = (LinearLayout)inflater.inflate(R.layout.dashboard_fragment,              container, false);