使用setOnClickListener更改setConetentView会导致程序崩溃(NullPointerException)

时间:2014-11-12 11:03:46

标签: android android-layout button nullpointerexception

所以我的程序工作正常,直到我想添加我的" mainmenu"。我想按下我的主菜单上的一个按钮,然后转到" start_board",这就是我基本上做的新内容。如果我没有提供足够的信息,请通知我,我对编程很陌生。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainmenu);  

    Button splayButton = (Button) findViewById(R.id.splay);

    splayButton.setBackgroundColor(Color.TRANSPARENT);

    splayButton.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v) {
            setContentView(R.layout.start_board);

        //code, code and more code

        }
    }); 
}

mainmenu XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mainmenu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/mainmenu" >

<Button
    android:id="@+id/splay"
    android:layout_width="195dp"
    android:layout_height="64dp"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" />

</RelativeLayout>

logcat的

11-12 11:41:21.272: E/AndroidRuntime(22244): FATAL EXCEPTION: main
11-12 11:41:21.272: E/AndroidRuntime(22244): Process: com.gerfort.gerfortrps, PID: 22244
11-12 11:41:21.272: E/AndroidRuntime(22244): java.lang.NullPointerException
11-12 11:41:21.272: E/AndroidRuntime(22244):    at com.gerfort.gerfortrps.MainActivity$4.onClick(MainActivity.java:185)
11-12 11:41:21.272: E/AndroidRuntime(22244):    at android.view.View.performClick(View.java:4637)
11-12 11:41:21.272: E/AndroidRuntime(22244):    at     android.view.View$PerformClick.run(View.java:19422)
11-12 11:41:21.272: E/AndroidRuntime(22244):    at     android.os.Handler.handleCallback(Handler.java:733)
11-12 11:41:21.272: E/AndroidRuntime(22244):    at android.os.Handler.dispatchMessage(Handler.java:95)
11-12 11:41:21.272: E/AndroidRuntime(22244):    at android.os.Looper.loop(Looper.java:136)
11-12 11:41:21.272: E/AndroidRuntime(22244):    at android.app.ActivityThread.main(ActivityThread.java:5586)
11-12 11:41:21.272: E/AndroidRuntime(22244):    at java.lang.reflect.Method.invokeNative(Native Method)
11-12 11:41:21.272: E/AndroidRuntime(22244):    at java.lang.reflect.Method.invoke(Method.java:515)
11-12 11:41:21.272: E/AndroidRuntime(22244):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
11-12 11:41:21.272: E/AndroidRuntime(22244):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
11-12 11:41:21.272: E/AndroidRuntime(22244):    at dalvik.system.NativeStart.main(Native Method)

有什么想法吗?提前谢谢!

1 个答案:

答案 0 :(得分:0)

使用Fragments。并且当用户按下按钮时使用事务来更改当前UI