recycleler查看片段中的零点异常

RJB*_*RJB 1 android android-fragments android-recyclerview

我有片段的recyclerview.当我运行应用程序时,我收到以下消息.

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
Run Code Online (Sandbox Code Playgroud)

我搜索过并找到了类似问题的人,但它没有帮助我.片段中的recyclerview为null.这是我的代码:

我在onCreate上调用主要活动中的片段:

 FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
    trans.add(R.id.recycle_view_container, recyclerViewFragment, RECYCLER_FRAGMENT);
    trans.commit();
    trans.show(recyclerViewFragment);
Run Code Online (Sandbox Code Playgroud)

这是我的recyclerfragment:

public class RecyclerViewFragment extends Fragment

private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
static SQLiteDatabase db;
ArrayList<MyMarker> markerArrayList;
private MyAdapter adapter;
private String TAG = "recyclerview fragment";

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_recycler_view, container, false);


    recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_in_fragment);

    recyclerView.setHasFixedSize(true);

    layoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(layoutManager);

    adapter = new MyAdapter(markerArrayList, this);
    recyclerView.setAdapter(adapter);

    return view;
Run Code Online (Sandbox Code Playgroud)

这是我的recyclelerview片段的xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RecyclerView.RecyclerViewFragment"
android:background="#a6ffffff">

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view_in_fragment"
    android:scrollbars="vertical"
    android:layout_below="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />
Run Code Online (Sandbox Code Playgroud)

非常感谢您的帮助.

Sha*_*ari 6

您应该使用 onViewCreated()访问视图

@Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
     recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_in_fragment);

    recyclerView.setHasFixedSize(true);

    layoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(layoutManager);

    adapter = new MyAdapter(markerArrayList, this);
    recyclerView.setAdapter(adapter);
}
Run Code Online (Sandbox Code Playgroud)