findViewById()什么时候返回null?

时间:2011-06-15 17:39:22

标签: android android-layout

我的findViewById()中有一个看似无辜的onCreate(),它不断返回null:

mCheckLicenseButton = (Button) findViewById(R.id.btn_checkout);

我的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" />

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

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

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

2 个答案:

答案 0 :(得分:6)

我要打电话给你,并说你在调用之前没有调用setContentView(R.layout.main),你必须这样做。

答案 1 :(得分:5)

您需要在之前调用setContentView:

setContentView(R.layout.main);
相关问题