[英]Android : surfaceView cannot getHolder() in onCreate(), must in onResume()
In my activity, I has some views and a surfaceView
. 在我的活动中,我有一些视图和
surfaceView
。
Here is my first code in onCreate()
这是我在
onCreate()
第一个代码
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
upBtn = (Button) findViewById(R.id.upBtn);
// and more widget here
surface = (SurfaceView) findViewById(R.id.surfaceView);
this.holder = surface.getHolder(); // NullPointerException
setContentView(R.layout.view);
If I change the above code by taking surfaceView
and getHolder()
in onResume()
(I have tried many times to have this result), no error: 如果我通过在
onResume()
surfaceView
和getHolder()
来更改上述代码(我已经尝试了很多次以获得此结果),则不会出现错误:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
upBtn = (Button) findViewById(R.id.upBtn);
// and more widget here
// surface = (SurfaceView) findViewById(R.id.surfaceView); //cancel
// this.holder = surface.getHolder(); // cancel
setContentView(R.layout.view);
public void onResume() {
surface = (SurfaceView) findViewById(R.id.surfaceView);
this.holder = surface.getHolder(); // No Error now
Please explain for me. 请给我解释一下。
Becaues you need to call 由于您需要致电
setContentView(R.layout.layoutXML);
before you call findViewById(R.id.viewID)
. 在调用
findViewById(R.id.viewID)
。 that is why your findview by id returning nul, and you probably getting nullPointerException when you are calling surfaceView.getHolder 这就是为什么id通过id返回nul的findview的原因,并且在调用surfaceView.getHolder时可能会得到nullPointerException
Suggested solution is, Create a layout.xml file which should have surfaceView inside any layout. 建议的解决方案是,创建一个layout.xml文件,该文件的任何布局内均应具有surfaceView。
in your Activity's oncreate call setContentView(R.layout.layoutXML);
在您的Activity的oncreate调用
setContentView(R.layout.layoutXML);
and after this you can retrieve surface view by findViewByID and do whatever you want with it. 然后,您可以通过findViewByID检索表面视图,并对其进行任何操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.