我在工程中使用button的時候遇到了這麼一個異常
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
簡單來說,就是button爲空,你可能會說,這很簡單吶,是不是你的button沒有綁定xml或者綁定錯誤?那我給你看我的代碼
完全和平時用的一致對吧,而且我的工程裏還有很多這樣的,但是它們都運行正常。
解決方案
上面我可能寫得不是很詳細,其實我這個button不是放在與這個活動綁定的那個xml文件中的,而是放在一個Fragment當中,具體看下面的圖
FragmentTestActivity的xml文件(裏面的Button是我用來測試用的):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.item_activity.fragement.FragmentTestActivity"
android:baselineAligned="false">
<Button
android:id="@+id/btn_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="button"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<FrameLayout
android:id="@+id/left_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"/>
<FrameLayout
android:id="@+id/right_fragment"
android:layout_weight="3"
android:layout_width="0dp"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
</LinearLayout>
LeftFragment的xml文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn_replaceFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="@string/fragment"/>
</LinearLayout>
所以目前得到的結論應該是:
因爲這個button不是在綁定的這個活動的xml文件當中,所以setContentView不能和這個button的點擊事件同時存在
所以目前我的解決方案是將這個button_replaceFragment的聲明和點擊事件放在LeftFragment當中去實現。
這裏又要注意:點擊事件需要放在onActivityCreate()當中去實現,如果放在onCreateView()中會導致點擊事件失效,因爲onCreateView()只是進行rootView的初始化