发现ViewById时出现Nullpointerexception

时间:2011-12-01 12:28:09

标签: android nullpointerexception xml-layout

我在oncreate方法的最后一行中有nullpointerexception

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.blindassistantmain);

    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    BlindTableLayout tableLayout = (BlindTableLayout) findViewById(R.id.blindTableLayout);
    BlindButton btn = (BlindButton) findViewById(R.id.firstButton);
    btn.setText("Lorem Ipsum"); //here is the nullpointer
 }

我的XML看起来像这样

<com.simekadam.blindassistant.ui.BlindTableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/blindTableLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="0px"
    android:layout_margin="0px"
    android:focusable="true"
    android:stretchColumns="*"

    android:background="@android:color/white"
    >
    <TableRow android:layout_weight="1">
        <com.simekadam.blindassistant.ui.BlindButton android:id="@+id/firstButton"  android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="0.5"/>
        <com.simekadam.blindassistant.ui.BlindButton android:id="@+id/secondButton" android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="0.5"/>
    </TableRow>
    <TableRow android:layout_weight="1">
        <com.simekadam.blindassistant.ui.BlindButton android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="1"/>
        <com.simekadam.blindassistant.ui.BlindButton android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="1"/>
    </TableRow>
    <TableRow android:layout_weight="1">
        <com.simekadam.blindassistant.ui.BlindButton android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="1"/>
        <com.simekadam.blindassistant.ui.BlindButton android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="1"/>
    </TableRow>

</com.simekadam.blindassistant.ui.BlindTableLayout>

有人知道我的代码中有什么问题吗? 谢谢

2 个答案:

答案 0 :(得分:1)

尝试:

BlindTableLayout tableLayout = (BlindTableLayout) findViewById(R.id.blindTableLayout);
BlindButton btn = (BlindButton) tableLayout.findViewById(R.id.firstButton);

这样您就可以在tableLayout中找到该视图,例如 tableLayout.findViewById (R.id.firstButton)。

答案 1 :(得分:0)

您是否尝试清理项目? (“项目” - &gt;“清洁”) 这有助于我有时遇到像你这样的问题。 别忘了检查“自动构建”。

顺便说一下。你能在R.java中找到你的按钮吗?