2015-06-19 202 views
-3

我只是不明白爲什麼它總是返回null((FrameLayout)findViewById(R.id.qrCameraPreview);)。我希望你能幫助我。findviewbyid在Android中返回null

import android.app.Activity; 
import android.hardware.Camera; 
import android.os.Build; 
import android.os.Bundle; 
import android.os.Handler; 
import android.view.View; 
import android.widget.FrameLayout; 

import net.sourceforge.zbar.Config; 
import net.sourceforge.zbar.Image; 
import net.sourceforge.zbar.ImageScanner; 
import net.sourceforge.zbar.Symbol; 
import net.sourceforge.zbar.SymbolSet; 


public class QRCodeReaderActivity extends Activity { 
    private Handler autoFocusHandler; 
    private Camera camera; 
    private CameraPreview cameraPreview; 
    private ImageScanner QRCodeScanner; 
    private boolean QRCodeScanned = false; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     initiate(); 

     if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) 
     { 
      //Old and deprecated implementation of Camera. 
      initiateOldCamera(); 
     } 

     else 
     { 
      //New and improved version of CameraManager. 
      //todo: Implement this. But for now use old implementation. 
      initiateOldCamera(); 
     } 

     QRCodeScanner = new ImageScanner(); 
     QRCodeScanner.setConfig(0, Config.X_DENSITY, 3); 
     QRCodeScanner.setConfig(0, Config.Y_DENSITY, 3); 

     cameraPreview = new CameraPreview(this, camera, previewCameraCallback, autoFocusCallback); 
    } 

    private void initiate() 
    { 
     FrameLayout preview = (FrameLayout) findViewById(R.id.qrCameraPreview); 
     preview.addView(cameraPreview); 
    } 

版式文件

<TextView 
    android:id="@+id/qrHeader" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/point_camera_at_qr_code" 
    style="@style/textHeader"/> 

<Button 
    android:id="@+id/qrCancelButton" 
    android:text="@string/cancel" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    style="@style/buttonLargeWhite" 
    android:layout_alignParentBottom="true"/> 

<FrameLayout 
    android:id="@+id/qrCameraPreview" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_below="@id/qrHeader" 
    android:layout_above="@id/qrCancelButton" 
    android:background="@color/PrinchWhite" 
    android:padding="3dp"/> 
+0

您是否從適當的佈局中找到視圖? –

+0

是的,它是相同的佈局。我可以只上傳佈局屁股 – Sulby

+5

您必須在佈局標識符的oncreate中調用setContentView。 – Neil

回答

1

更改像這樣。

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.YourLayoutName); 

}

之前設置你的內容查看您正在搜索的搜索,那是什麼導致了錯誤。

1

你需要

setContentView(R.layout.x); // replace x with whatever your layout is called 

onCreate(Bundle savedInstanceState)