-1

尝试以textView编程方式向片段添加时出现空指针异常。

我认为上下文返回 null 但我可能是错的。坠机发生在startMenu.addView(tv);

public class TabFragment1 extends Fragment {

View inflatedView;
Context context = null;
private Bundle mBundle;
private LinearLayout startMenull ;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    if (container == null) {

        return null;
    }

    if (inflatedView != null) {
        ViewGroup parent = (ViewGroup) inflatedView.getParent();


        if (parent != null)
            parent.removeView(inflatedView);
    }
    try {

        inflatedView = inflater.inflate(R.layout.start_menu, container,
                false);
        context = getActivity().getApplicationContext();
        //startMenu = (LinearLayout) getActivity().findViewById(R.id.start_menull);
        startMenu = (LinearLayout) getLayoutInflater(mBundle).inflate(R.id.start_menull, null);
        TextView tv = new TextView(context);
        tv.setId(1);
        tv.setText("Here is the text Box");    
        startMenu.addView(tv);
    } catch (InflateException e) {

    }
    return inflatedView;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 
    mBundle = savedInstanceState;
}

}

更新以上代码 9/16 3:48

已解决:在 try/catch

inflatedView = inflater.inflate(R.layout.start_menu, container,
                false);
        context = getActivity().getApplicationContext();
        startMenull =((LinearLayout) inflatedView.findViewById(R.id.start_menull));
        TextView tv = new TextView(context);
        tv.setId(1);
        tv.setText("Here is the text Box");    
        startMenull.addView(tv);
4

2 回答 2

0

那时上下文不能为空,因为他正在使用 applicationContext。

但开始菜单是!null 因为 onCreate 在 onCreateView 之前被调用。所以你必须先给 View 充气,你应该在 onCreateView 而不是 onCreate 中这样做。

刚刚注意到您在 onCreateView 中膨胀了视图,但您仍然无法在 onCreate 中访问它,因为它在 onCreateView 之前被调用。

请参阅 Android 生命周期。http://developer.android.com/images/fragment_lifecycle.png

public class TabFragment1 extends Fragment {

View inflatedView;

public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

    inflatedView = inflater.inflate(R.layout.start_menu, container,false);

    LinearLayout startMenu = (LinearLayout) inflatedView.findViewById(R.id.start_menu);
    TextView tv = new TextView(getActivity());
    tv.setId(1);
    tv.setText("Here is the text view");    
    startMenu.addView(tv);

    return inflatedView;
 }
}

如果我想做你正在做的事情,我会这样做。为什么要检查容器是否为空?或者你为什么认为 inflatedView 是 != null?

于 2013-09-16T19:20:43.160 回答
-1

在 onCreateView 之前调用 onCreate。阅读生命周期。

于 2013-09-16T19:27:55.480 回答