回收器查看片段

时间:2016-03-10 21:09:15

标签: 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

我搜索并发现有类似问题的人,但它没有帮助我。片段中的recyclerview为null。这是我的代码:

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

 FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
    trans.add(R.id.recycle_view_container, recyclerViewFragment, RECYCLER_FRAGMENT);
    trans.commit();
    trans.show(recyclerViewFragment);

这是我的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;

这是我的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"
    />

非常感谢您的帮助。

1 个答案:

答案 0 :(得分: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);
}