findViewById()什么时候返回null?

ef2*_*011 2 android android-layout

我有这个看似无辜findViewById()的我onCreate()不断返回null:

mCheckLicenseButton = (Button) findViewById(R.id.btn_checkout);
Run Code Online (Sandbox Code Playgroud)

res/layout/main.xml清楚地包含这个按钮:

<Button android:id="@+id/btn_checkout" 
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:layout_below="@+id/top_textview"
    android:layout_alignParentRight="true"
    android:text="Check License" />
Run Code Online (Sandbox Code Playgroud)

所以我不明白为什么findViewById()返回null.

在什么情况下findViewById()返回null?

显然,findViewById()没有成功找到布局资源,但有什么可能解释这个?

Max*_*mus 6

我打算走出去,说你在调用之前没有调用setContentView(R.layout.main),你必须这样做.


MBy*_*ByD 5

您需要在调用setContentView之前:

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