findviewbyid给出了意外的nullpointer异常

时间:2014-11-15 00:18:37

标签: java android

我刚创建了简单的应用并添加了按钮。

MyActivity.java

package com.example.myapp;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;

public class MyActivity extends Activity {
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    Button buttonClick = (Button) findViewById(R.id.button);
}

这是xml文件

Main.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
        >
    <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" android:layout_gravity="center_horizontal">
        <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="Hello World, MyActivity"
                android:layout_alignParentTop="true" android:layout_alignParentStart="true"/>
        <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="New Button"
                android:id="@+id/button" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true"
                android:layout_marginBottom="60dp"/>
    </RelativeLayout>
</LinearLayout>

Androidmanifest与ide

创建的相同

所以当我尝试运行这段代码时,我会回复由findviewbyid引起的nullpointer异常我做错了什么?

1 个答案:

答案 0 :(得分:2)

Button buttonClick = (Button) findViewById(R.id.button);放在onCreate内。例如:

Button buttonClick;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    buttonClick = (Button) findViewById(R.id.button);
}