用Eclipse新建一个简单应用,添加一个简单按钮,显示没有问题,就是添加响应后,一运行就出错退出。
调试一下,发现 findViewById函数返回null。
在网上找了好多,被搞的晕了,后来才找到原因。
以前android 没有Fragment,添加的按钮都加到activity_main.xml,现在有Fragment,添加的按钮都加到fragment_main.xml。
在onCreate中, setContentView(R.layout.activity_main); 所以 ContentView是activity_main, 当然找不到按钮。
而我以前都习惯在onCreat中初始化控件,所以出现这个问题。
在onCreateView中,可以找的fragment_main,如下调用返回正常:
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mButton = (Button)rootView. findViewById(R.id.button1);
如果不是在onCreatView里,可以下面方式:
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rootView = (View)inflater.inflate(R.layout.fragment_main, null);
mButton = (Button)rootView. findViewById(R.id.button1);