记录一次Fragment中使用button的失灵?还是错误?

我在工程中使用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的初始化

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章