Fragment 控件空指针问题

来源:互联网 发布:吉他扒带软件 编辑:程序博客网 时间:2024/05/20 14:28

错误情景描述:

activity_main:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:background="@color/white">    <fragment        android:id="@+id/id_fragment_notice"        android:name="com.view.fragment.NoFragment"        android:layout_width="match_parent"        android:layout_height="match_parent" /></LinearLayout>

在获取 NoFragment 里的控件时,总是报空指针,下面是获取代码
@Nullable@Overridepublic View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {    return inflater.inflate(R.layout.fragment_notice, null);}
@Overridepublic void onActivityCreated(@Nullable Bundle savedInstanceState) {    super.onActivityCreated(savedInstanceState);    btn_all = (Button) getView().findViewById(R.id.btn_all_notice_drawer);}
解决办法:
@Nullable@Overridepublic View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {    View view = inflater.inflate(R.layout.fragment_notice_drawerlayout, container, false);    // widget    drawerLayout = (DrawerLayout) view.findViewById(R.id.drawerlayout_noticefragment);    return view;}
原因是什么我现在也还不太清除,这算是记录下来给自己以及可能需要的朋友看下

原创粉丝点击