尝试以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);