在我的 Activity 中,我有一些 View 和一个 surfaceView
。
这是我在 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);
如果我通过在 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
请帮我解释一下。
最佳答案
因为你需要打电话
setContentView(R.layout.layoutXML);
在调用findViewById(R.id.viewID)
之前。这就是为什么你的findview by id返回nul,并且当你调用surfaceView.getHolder时你可能会得到nullPointerException
建议的解决方案是,创建一个layout.xml 文件,该文件应在任何布局中包含surfaceView。
在 Activity 的 oncreate 调用 setContentView(R.layout.layoutXML);
中,之后您可以通过 findViewByID 检索表面 View 并对其执行任何您想要的操作。
关于java - Android : surfaceView cannot getHolder() in onCreate(), 必须在 onResume() 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11489792/