gpt4 book ai didi

android - fragment 中的 recyclerview 空指针异常

转载 作者:行者123 更新时间:2023-11-29 14:46:26 26 4
gpt4 key购买 nike

我在 fragment 中有一个 recyclerview。当我运行该应用程序时,我收到以下消息。

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

我已经搜索并找到了有类似问题的人,但它并没有帮助我。 fragment 中的 recyclerview 为空。这是我的代码:

我在 onCreate 上调用主要 Activity 中的 fragment :

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

这是我的回收 fragment :

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;

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

如果您能提供帮助,非常感谢。

最佳答案

您应该使用onViewCreated() 来访问 View

@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);
}

关于android - fragment 中的 recyclerview 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35927321/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com