繁体   English   中英

Android findViewById始终返回null

[英]Android findViewById always returns null

目前,我正在尝试使用Android NDK和Live555构建流应用程序。 但是我当前的问题更加令人困惑。 我创建了CustomPreviewClass来显示实际的相机图片。 但是不幸的是,当我尝试访问视图时,方法findViewById()始终返回null。 为什么? 有人有主意吗?

这是我的活动:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    preview = (CameraPreview) findViewById(R.id.surfaceView1); // returns null
    if (preview == null) Log.d("Test", "Preview is null");

    final Button buttonStart = (Button) findViewById(R.id.buttonStart);
    buttonStart.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            try {
                startRecording();
            } catch (IOException e) {
                e.printStackTrace();
            }
            buttonStart.setEnabled(false);
        }
    });

    final Button buttonStop = (Button) findViewById(R.id.buttonStop);
    buttonStop.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            stopRecording();
            buttonStart.setEnabled(true);
        }
    });
}

只是一点说明:按钮的findViewById()工作正常...

activity_main.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="de.douglasmedia.LiveCam.MainActivity" >

<de.douglasmedia.LiveCam.views.CameraPreview
    android:id="@+id/surfaceView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</de.douglasmedia.LiveCam.views.CameraPreview>

<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/buttonStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start" >
    </Button>

    <Button
        android:id="@+id/buttonStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop" >
    </Button>
</LinearLayout>

相机预览:

...
public CameraPreview(Context context, AttributeSet attrs) {
    this(context);
}

public CameraPreview(Context context) {
    super(context);
    SurfaceHolder holder = getHolder();
    holder.addCallback(this);
}

@Override
public void surfaceCreated(SurfaceHolder holder) {
    synchronized (surfaceCreationSync) {
        surfaceCreatedHolder = holder;
        surfaceCreationSync.notifyAll();
    }
}
...

谢谢你的帮助!

我已经自己解决了这个问题。 问题是,我错过了CameraPreview类中带有3个参数的构造函数。 因此,我添加了此构造函数,一切正常……

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM