NullPointerException异常时findingViewById异常、NullPointerException、findingViewById

2023-09-04 23:25:46 作者:Scavengers[拾荒者]

我有NullPointerException异常在我的onCreate方法的最后一行

I have nullpointerexception in last line of my oncreate method

 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看起来像这样

My XML looks like this

<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>

有谁知道什么是错在我的code? 谢谢

Does anybody know whats wrong in my code? Thank you

推荐答案

尝试:

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

这样你发现内的视图中的 tableLayout ,例如 tableLayout.findViewById (R.id.firstButton)。

This way you're finding the view within your tableLayout, e.g tableLayout.findViewById(R.id.firstButton).

 
精彩推荐