Android:surfaceView不能在onCreate()中使用getHolder(),必须在onResume()中

hqt*_*hqt 0 java layout android surfaceview surfaceholder

在我的活动中,我有一些观点和一个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);
Run Code Online (Sandbox Code Playgroud)

如果我通过take surfaceViewgetHolder()in 更改上面的代码onResume()(我已经多次尝试过这个结果),没有错误:

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);
Run Code Online (Sandbox Code Playgroud)
public void onResume() {
    surface = (SurfaceView) findViewById(R.id.surfaceView);     
    this.holder = surface.getHolder(); // No Error now
Run Code Online (Sandbox Code Playgroud)

请解释一下.

AAn*_*kit 5

你需要打电话

setContentView(R.layout.layoutXML); 
Run Code Online (Sandbox Code Playgroud)

在你打电话之前findViewById(R.id.viewID).这就是为什么你的findview通过id返回nul,你可能在调用surfaceView.getHolder时得到nullPointerException

建议的解决方案是,创建一个layout.xml文件,该文件应该在任何布局中包含surfaceView.

在您的Activity的oncreate调用中 setContentView(R.layout.layoutXML);,之后您可以通过findViewByID检索表面视图并随意执行任何操作.