XML代碼SetBackgroundColour方法:空指針異常請在Android
<RelativeLayout
android:layout_width="193dp"
android:layout_height="100dp"
android:background="@color/RED"
android:layout_alignParentBottom="true"
android:id="@+id/butt1"></RelativeLayout>
<RelativeLayout
android:layout_width="193dp"
android:layout_height="100dp"
android:background="@color/YELLOW"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:id="@+id/butt2"></RelativeLayout>
<RelativeLayout
android:layout_width="193dp"
android:layout_height="100dp"
android:background="@color/BLUE"
android:layout_above="@+id/butt2"
android:layout_alignParentRight="true"
android:id="@+id/butt3"></RelativeLayout>
<RelativeLayout
android:layout_width="193dp"
android:layout_height="100dp"
android:background="@color/GREEN"
android:layout_above="@+id/butt1"
android:id="@+id/butt4"></RelativeLayout>
Java代碼:
butt4 = (RelativeLayout)findViewById(R.id.butt4);
butt3 = (RelativeLayout)findViewById(R.id.butt3);
butt1 = (RelativeLayout)findViewById(R.id.butt1);
butt2 = (RelativeLayout)findViewById(R.id.butt2);
butt1.setBackgroundColor(Color.RED);
butt2.setBackgroundColor(Color.BLUE);
butt3.setBackgroundColor(Color.GREEN);
butt4.setBackgroundColor(Color.YELLOW);
日誌:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
'void android.view.View.setBackgroundColor(int)' on a null object reference
at com.example.chirag.red.Hard.change(Hard.java:73)
at com.example.chirag.red.Hard.onCreate(Hard.java:53)
at android.app.Activity.performCreate(Activity.java:6672)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
的應用程序崩潰,每到這個活動啓動。該錯誤總是在行「butt1.setBackgroundColor()」,它給了我一個空指針異常。我給佈局一個ID,引用它,並且還傳遞了一種顏色作爲方法中的參數。我真的不知道我哪裏出了問題。請幫忙!
顯示完全相同的錯誤! – Chirag
你的xml還有什麼?是父母包圍的相對佈局嗎? – DroiDev
還有別的東西你沒有向我們展示。我運行了一個測試應用程序,我給你的代碼工作。所以更多的是它比你告訴我們的更多。 – DroiDev